<?php
//获取检测单位
function getClentOnly($client_id = ''){
    global $DB;
    if($client_id !=''){
        $client_info = $DB->fetch_one_assoc("SELECT fzx_id,name,liaison,phone_number,address FROM `client` WHERE  `id`='{$client_id}'");
        $client_info['text'] = $client_info['name'];
    }else{
        $client_sql = "SELECT fzx_id,name,liaison,phone_number,address FROM `client`";
        $client_query = $DB->query($client_sql);
        $i = 0;
        while ($row = $DB->fetch_assoc($client_query)) {
            $row['value'] = $i;
            $row['text'] = $row['name'];
            $client_info[] = $row;
            $i ++;
        }
    }
    return $client_info;
}
//搜索检测单位
function selectClent($client_name = ''){
    global $DB;
    $client_sql = "SELECT fzx_id,name,liaison,phone_number,address FROM `client` WHERE  `name` like '%{$client_name}%'";
    $client_query = $DB->query($client_sql);
    $i = 0;
    while ($row = $DB->fetch_assoc($client_query)) {
        $row['value'] = $i;
        $row['text'] = $row['name'];
        $client_arr[] = $row;
        $i ++;
    }
    return $client_arr;
}
//添加检测单位
function addClent($clent_data = array()){
    global $DB;
    $sql = insertSql('clent' , $clent_data);
    return $DB->query($sql);

}
//获取站点
function getSites($site_id = ''){
    global $DB;
    if($site_id != ''){
        $siets = $DB->fetch_one_assoc("SELECT fzx_id,site_name,site_address FROM `sites` WHERE  `id`='{$site_id}'");
        $siets['text'] = $siets['site_name'];
    }else{
        $sql = "SELECT fzx_id,site_name,site_address FROM `sites` WHERE  `act`='1' AND `site_type` IN('0','3') ORDER BY `id` DESC LIMIT 1000";
        $query = $DB->query($sql);
        $siets = [];
        $i = 0;
        while ($row = $DB->fetch_assoc($query)) {
            $row['value'] = $i;
            $row['text'] = $row['site_name'];
            $siets[] = $row;
            $i ++;
        }
    }

    return $siets;
}
//搜索站点
function selectSites($site_name = ''){
    global $DB;
    $sites_sql = "SELECT id,fzx_id,site_name,site_address FROM `sites` WHERE  `site_name` like '%{$site_name}%'";
    $sites_query = $DB->query($sites_sql);
    $i = 0;
    while ($row = $DB->fetch_assoc($sites_query)) {
        $row['value'] = $row['id'];
        $row['text'] = $row['site_name'];
        $sites_arr[] = $row;
        $i ++;
    }
    return $sites_arr;
}
function getSitesItem($site_name = ''){
    global $DB;
    $site_info = $DB->fetch_one_assoc("SELECT fzx_id,site_name,site_address FROM `sites` WHERE  `site_name`='{$site_name}'");
    return $site_info;
}
//获取水样类型
function getLeixings(){
    global $DB;
    $sql = "SELECT id,lname,e_lname,bar_code_mark FROM `leixing` WHERE  `act`='1' AND `parent_id` = '0'";
    $query = $DB->query($sql);
    $leixings = [];
    $i = 0;
//    while ($row = $DB->fetch_assoc($query)) {
//        $sql_item = "SELECT lname,e_lname,bar_code_mark FROM `leixing` WHERE  `act`='1' AND `parent_id` = '{$row['id']}'";
//        $query_item = $DB->query($sql_item);
//        $item = [];
//        $n = 0;
//        while ($row_item = $DB->fetch_assoc($query_item)) {
//            $row_item['value'] = $n;
//            $row_item['text'] = $row_item['lname'];
//            $item[] = $row_item;
//            $n ++;
//        }
//        $row['item'] = $item;
//        $row['value'] = $i;
//        $row['text'] = $row['lname'];
//        $leixings[] = $row;
//        $i ++;
//    }
    while ($row = $DB->fetch_assoc($query)) {
        $sql_item = "SELECT id,lname,e_lname,bar_code_mark FROM `leixing` WHERE  `act`='1' AND `parent_id` = '{$row['id']}'";
        $query_item = $DB->query($sql_item);
        $row['value'] = $row['id'];
        $row['text'] = $row['lname'];
        $leixings[] = $row;
        $i ++;
        while ($row_item = $DB->fetch_assoc($query_item)) {
            $row_item['value'] = $row_item['id'];
            $row_item['text'] = '--'.$row_item['lname'];
            $leixings[] = $row_item;
            $i++;
        }

    }
    return $leixings;
}
//获取检测标准
function getJcbz(){
    global $DB;
    $sql = "SELECT id,module_value1,module_value2,module_value4,module_value6 FROM `n_set` WHERE  `act`='1' AND `module_name` = 'jcbz_bh'";
    $query = $DB->query($sql);
    $jcbz = [];
    $i = 0;
    while ($row = $DB->fetch_assoc($query)) {
        $bz = array();
        $bz['text'] = $row['module_value1']; //标准名称
        $bz['sylx'] = $row['module_value2']; //关联的水样类型
        $bz['syfl'] = $row['module_value4']; //水样分类
        $bz['hz'] = $row['module_value6']; //后缀
        $bz['value'] = $row['id']; //后缀
        $jcbz[] = $bz;
        $i ++;
    }
    return $jcbz;
}
//获取检测项目模板
function getXmmb(){
    global $DB;
    $sql = "SELECT id,module_value1,module_value2,module_value4 FROM `n_set` WHERE  `act`='1' AND `module_name` = 'xmmb'";
    $query = $DB->query($sql);
    $xmmb_list = [];
    $i = 0;
    while ($row = $DB->fetch_assoc($query)) {
        $xmmb = array();
        $xmmb['text'] = $row['module_value2'];
        $xmmb['jcxm'] = $row['module_value1'];
        $xmmb['value'] = $row['module_value1'];
        $xmmb['price'] = $row['module_value4'];
        $xmmb['id'] = $row['id'];
        $xmmb_list[] = $xmmb;
        $i ++;
    }
    return $xmmb_list;
}
//获取检测项目
function getJcxm($id){
    global $DB;
    $jcxm_value = [];
    if($id){
        $jcxm_value = $DB->fetch_one_assoc("SELECT xm.id,xm.value_C,xm.fenlei,xm.is_xcjc,xm.seq,xm.price
					FROM `xmfa` AS fa
					RIGHT JOIN `assay_value` AS xm ON fa.xmid=xm.id
					WHERE fa.act='1' and xm.id = '{$id}'");
    }else {
        $xm_query = $DB->query("
					SELECT xm.id,xm.value_C,xm.fenlei,xm.is_xcjc,xm.seq,xm.price
					FROM `xmfa` AS fa
					RIGHT JOIN `assay_value` AS xm ON fa.xmid=xm.id
					WHERE fa.act='1'
					GROUP BY fa.xmid
					ORDER BY xm.seq,xm.id
				");
        $jcxm = [];
        while ($row = $DB->fetch_assoc($xm_query)) {
            if (empty($row['fenlei'])) {
                $row['fenlei'] = '未分类';
            }
            $jcxm_value[$row['fenlei']][] = $row;
        }
    }
    return $jcxm_value;
}

//添加委托信息
function addCustomer($post , $openid , $id = ''){
    global $DB,$global,$dw_biaozhi;
    include_once "../customer_manage/get_code.php";
    include_once "../data_statistics/report_data_func_new.php";

    $client_info = $DB->fetch_one_assoc("SELECT * FROM `client` WHERE `name`='{$client_name}' order by id desc");
    if (!$client_info) {
        $DB->query("INSERT INTO `client` SET `name`='{$post['client_name']}',`liaison`='{$post['liaison']}',`phone_number`='{$post['phone_number']}',`address`='{$post['client_address']}',`email`='{$post['email']}',`fax`='{$post['fax']}',`postal_code`='{$post['postal_code']}'");
        $client_info['id'] = $DB->insert_id();
        $client_info['name'] = $post['client_name'];
        $client_info['liaison'] = $post['liaison'];
        $client_info['phone_number'] = $post['phone_number'];
        $client_info['address'] = $post['client_address'];
        $client_info['email'] = $post['email'];
        $client_info['fax'] = $post['fax'];
        $client_info['postal_code'] = $post['postal_code'];
    }
    if (!$client_info) {
        return false;
    }
    //获取配置数据
    $individual_dir_name = "../customer_manage/json/{$dw_biaozhi}";
    if (!file_exists("{$individual_dir_name}/customer_add_field.json")){
        var_dump(33);
        $individual_dir_name = "../customer_manage/json/default";
    }
    $customer_info_all_json = file_get_contents("{$individual_dir_name}/customer_add_field.json");
    $customer_info_all_json = str_replace(['__template_value__', '__template_default_selected_value__','_sample_origin_default_value_','__template_site_type_val__'], ['""',"",'""','""'], $customer_info_all_json);
    $customer_info_all_json_arr = json_decode($customer_info_all_json, true);
    $field_name_arr = [];
    $yp_arr = [];
//    var_dump($customer_info_all_json_arr['样品信息']);
//    die;
    foreach ($customer_info_all_json_arr as $c_k => $c_v){
        foreach ($c_v as $c_v_k =>$c_v_v){
            if(strstr($c_v_v['field'] , 'json[')){
                $field_ex = explode('json[', $c_v_v['field'] );
                $field_name = substr($field_ex[1] , 0 , -1);
                $field_name_arr[$field_name] = $c_v_v['field'];
            }
        }
        if($c_k == '样品信息'){
            $yp_arr = [];
            foreach ($c_v as $yp_t => $yp_v){
                $yp_arr[] = $yp_v['field'];
            }
        }

    }
//    var_dump($field_name_arr);
    foreach ($field_name_arr as $field_name_k => $field_name_v){
        if(isset($post[$field_name_k])){
            $field_ex_v = explode('[', $field_name_v );
            $post[$field_ex_v[0]][$field_name_k] = $post[$field_name_k];
            unset($post[$field_name_k]);
        }
    }
//    die;
//    var_dump($post['sample_value']);
//    die;
    foreach ($yp_arr as $y_k_arr => $y_arr){
//        var_dump($y_arr);
//        var_dump($post[$y_arr]);
        if(isset($post[$y_arr]) && !$post['sample_value'][$y_arr]){
            foreach ($post['sample_value']['site_name'] as $p){
                $post['sample_value'][$y_arr][] = $post[$y_arr];
            }
        }
        unset($post[$y_arr]);
    }
    if($post['sample_value']['cy_rqly']){
        $post['sample_value']['sample_add_json']['cy_rqly'] = $post['sample_value']['cy_rqly'];
        unset($post['sample_value']['cy_rqly']);
    }
    if($post['sample_value']['cyrq_price']){
        $post['sample_value']['sample_add_json']['cyrq_price'] = $post['sample_value']['cyrq_price'];
        unset($post['sample_value']['cyrq_price']);
    }
//    var_dump($post['sample_value']);
//    die;
    if($post['sample_add_json']){
        foreach ($post['sample_value']['site_name'] as $p) {
            $post['sample_value']['sample_add_json'][] = $post['sample_add_json'];
            $post['sample_value']['sample_line_id'][] = '';
        }
        unset($post['sample_add_json']);
    }
    $sub_action = $post['sub_action'];
    $sample_value = $post['sample_value'];
    $client_name = $post['client_name'];
    unset($post['sample_value']);
    unset($post['sub_action']);
    $post['client_name'] = $client_info['name'];
    $post['client_id'] = $client_info['id'];
    //保存数据
    if(!$id) {
        $customer_value = $post;
        $add_value_arr = [];
        foreach ($customer_value as $k => $v) {
            $field = $k;
            $value = "";
            if (is_array($v)) {
                $value = JSON($v);
            } else {
                $value = $v;
            }
            $add_value_arr[$field] = $value;
        }
        // 报告规定完成日期等于报告发送日期
        if ($global['customer']['bgSendDate_op_bgScTime']) {
            $add_value_arr['report_stipulate_completion_time'] = $add_value_arr['report_send_time'];
        }
        $real_pay = '';
        if (isset($add_value_arr['real_pay_price']) && empty($add_value_arr['real_pay_price'])) {
            if (!empty($add_value_arr['inspection_price'])) {
                $real_pay = $add_value_arr['inspection_price'];
                if (!empty($add_value_arr['other_price'])) {
                    $real_pay = $real_pay + $add_value_arr['other_price'];
                }
                if (!empty($add_value_arr['discount'])) {
                    $real_pay = $real_pay * $add_value_arr['discount'];
                }
            }
            $add_value_arr['real_pay_price'] = $real_pay;
            if ($add_value_arr['real_pay_price'] . '' != '') {
                $add_value_arr['real_pay_price'] = sprintf("%01.2f", $add_value_arr['real_pay_price']);
            }
        }

        // 创建人 todo
        $add_value_arr['create_user'] = $openid; //微信标识
        $add_value_arr['wx_user'] = $openid; //微信标识
        // 生成委托单编号时，所需的数据
        $get_customer_code_data_arr = [];
        if ($global['customer']['get_code_field'] == 'task_type' && isset($post['add_json']['task_type'])) {
            $get_customer_code_data_arr['task_type'] = $post['add_json']['task_type'];
        }
        // 赋值委托日期
        $get_customer_code_data_arr['entrust_date'] = $post['entrust_date'];
        //判断何时生成委托编号，global中配置
        if ($global['customer']['code_create'] == '2') {
            $add_value_arr['code'] = get_customer_code($get_customer_code_data_arr);
        } elseif ($global['customer']['code_create'] = '3') {
            if ($sub_action != '保存') {
                $add_value_arr['code'] = get_customer_code($get_customer_code_data_arr);
            }
        }
        // 判断是否存在现场检测项目（必须是采样或global开启了送样可下达现场项目的配置）
        if ($sample_value['xc_exam_value'] && ($post['sample_origin'] == '1' || $global['xd_cyrw']['sy_xcxm'])) {
            $add_value_arr['xc_exam_value'] = $sample_value['xc_exam_value'];
        } else {
            $add_value_arr['xc_exam_value'] = "";
        }
        unset($sample_value['xc_exam_value']);

        $new_customer_id = new_record("customer", $add_value_arr);
        if (!$new_customer_id) {
            var_dump(7);
            return false;
        }
        // 插入委托单样品表格数据
        $sample_line_id = $sample_value['sample_line_id'];
        unset($sample_value['sample_line_id']);
        $sample_line_name = $sample_value['site_name'];
        $sample_add_json = $sample_value['sample_add_json'];
        unset($sample_value['sample_add_json']);
        // 客户送样数据
        $sample_external_inspections = $sample_value['external_inspections'];
        foreach ($sample_line_id as $k => $v) {
            if (!$sample_line_name[$k]) {
                continue;
            }

            $add_sample_arr = [];
            foreach ($sample_value as $sample_k => $sample_v) {
                $add_sample_arr[$sample_k] = $sample_v[$k];
            }
            foreach ($sample_add_json as $json_key => $json_v) {
                $add_sample_arr['sample_add_json'][$json_key] = $json_v[$k];
            }
            // 循环客户送样数据
            if ($sample_external_inspections) {
                foreach ($sample_external_inspections as $exin_k => $exin_v) {
                    // 循环填写的数据值
                    if ($exin_v[$k]) {
                        // 根据配置获取项目名称和单位
                        $exk_name = $exk_unit = "";
                        foreach ($customer_info_all_json_arr['样品信息'] as $info_json_k => $info_json_v) {
                            if ($exin_k == $info_json_v['vid']) {
                                $exk_name = $info_json_k;
                                $exk_unit = $info_json_v['unit'];
                                break;
                            }
                        }
                        // 赋值 项目名称 单位 检测结果
                        $add_sample_arr['external_inspections'][$exin_k]['value'] = $exin_v[$k];
                        $add_sample_arr['external_inspections'][$exin_k]['name'] = $exk_name;
                        $add_sample_arr['external_inspections'][$exin_k]['unit'] = $exk_unit;
                    }
                }
                $add_sample_arr['external_inspections'] = JSON($add_sample_arr['external_inspections']);
            }
            $add_sample_arr['sample_add_json'] = JSON($add_sample_arr['sample_add_json']);
            $add_sample_arr['customer_id'] = $new_customer_id;
            $add_sample_arr['jc_yiju'] = join($add_sample_arr['jc_yiju'], '|');
            new_record("customer_rec", $add_sample_arr);
        }
        if ($sub_action == '保存') {
            return ['customer_id' => $new_customer_id];
        }
    }else{
        // 获取rec旧数据
        $old_rec_sql = $DB->query("SELECT * FROM `customer_rec` WHERE `customer_id`='{$id}'");
        $old_rec_arr = [];
        while($old_row = $DB->fetch_assoc($old_rec_sql)){
            $old_rec_arr[$old_row['id']] = $old_row;
        }
        $customer_value = $post;
        // 获取customer旧数据
        $customer_info = $DB->fetch_one_assoc("SELECT * FROM `customer` WHERE `id`='{$id}'");
        if($global['customer']['cy_yiju'] && $global['cy_tzd']['show_cy_yiju']){
            // 是否生成采样单，生成同步更新cy表采样依据
            if($customer_info['cyd_id']){
                $DB->query("UPDATE `cy` SET `cy_yiju`='{$customer_value['add_json']['cy_yiju']}' WHERE `id`='{$customer_info['cyd_id']}'");
            }
        }
        // 同步修改cy表数据
        if($customer_info['cyd_id']){
            $cyd_data = $DB->fetch_one_assoc("SELECT * FROM `cy` WHERE `id`='{$customer_info['cyd_id']}'");
            // 判断是否修改了委托单位
            if($cyd_data['cy_dept'] != $customer_value['client_name']){
                $DB->query("UPDATE `cy` SET `cy_dept`='{$customer_value['client_name']}' WHERE `id`='{$customer_info['cyd_id']}'");
            }
            // 判断是否修改了委托单位地址
            if($cyd_data['cy_dept_address'] != $customer_value['client_address']){
                $DB->query("UPDATE `cy` SET `cy_dept_address`='{$customer_value['client_address']}' WHERE `id`='{$customer_info['cyd_id']}'");
            }
            // 判断是否修改了联系人
            if($cyd_data['wtdw_lxr'] != $customer_value['liaison']){
                $DB->query("UPDATE `cy` SET `wtdw_lxr`='{$customer_value['liaison']}' WHERE `id`='{$customer_info['cyd_id']}'");
            }
            // 判断是否修改了联系电话
            if($cyd_data['wtdw_tel'] != $customer_value['phone_number']){
                $DB->query("UPDATE `cy` SET `wtdw_tel`='{$customer_value['phone_number']}' WHERE `id`='{$customer_info['cyd_id']}'");
            }
        }
        $update_value_arr = [];
        foreach ($customer_value as $k => $v) {
            $field = $k;
            $value = "";
            if (is_array($v)) {
                $value = JSON($v);
            } else {
                $value = $v;
            }
            $update_value_arr[$field] = $value;
        }
        // 是否开启了报告发送日期=报告规定完成日期new_record
        if($global['customer']['bgSendDate_op_bgScTime']){
            $update_value_arr['report_stipulate_completion_time'] = $update_value_arr['report_send_time'];
        }
        // 判断是否存在现场检测项目（必须是送样或开启了送样可下达现场项目的配置）
        if($sample_value['xc_exam_value'] && ($post['sample_origin'] == '1' || $global['xd_cyrw']['sy_xcxm'])){
            $update_value_arr['xc_exam_value'] = $sample_value['xc_exam_value'];
        }else{
            $update_value_arr['xc_exam_value'] = "";
        }
        unset($sample_value['xc_exam_value']);
        update_rec("customer", $update_value_arr, $id);
        // 修改委托单样品表格数据
        $sample_line_id = $sample_value['sample_line_id'];
        unset($sample_value['sample_line_id']);
        $sample_line_name = $sample_value['site_name'];
        $sample_add_json = $sample_value['sample_add_json'];
        unset($sample_value['sample_add_json']);
        // 客户送样数据
        $sample_external_inspections = $sample_value['external_inspections'];
        unset($sample_value['external_inspections']);
        foreach ($sample_line_id as $k => $sample_id) {
            if (!$sample_line_name[$k]) {
                continue;
            }
            $add_sample_arr = [];
            foreach ($sample_value as $sample_k => $sample_v) {
                if($global['jcbz_multiple_choice'] && $sample_k == 'jcyj'){
                    $sample_v[$k] = implode(",",$sample_v[$k]);
                }
                $add_sample_arr[$sample_k] = $sample_v[$k];
            }
            foreach ($sample_add_json as $json_key => $json_v) {
                foreach ($json_v as $json_key2 => $json_v2) {
                    $add_sample_arr['sample_add_json'][$json_key] = $json_v[$k];
                }
            }
            // 循环客户送样数据
            if($sample_external_inspections){
                foreach($sample_external_inspections as $exin_k => $exin_v){
                    // 循环填写的数据值
                    foreach($exin_v as $exin_k2 => $exin_v2){
                        if($exin_v[$k]){
                            // 根据配置获取项目名称和单位
                            $exk_name = $exk_unit = "";
                            foreach($customer_info_all_json_arr['样品信息'] as $info_json_k => $info_json_v){
                                if($exin_k == $info_json_v['vid']){
                                    $exk_name = $info_json_k;
                                    $exk_unit = $info_json_v['unit'];
                                    break;
                                }
                            }
                            // 赋值 项目名称 单位 检测结果
                            $add_sample_arr['external_inspections'][$exin_k]['value'] = $exin_v[$k];
                            $add_sample_arr['external_inspections'][$exin_k]['name'] = $exk_name;
                            $add_sample_arr['external_inspections'][$exin_k]['unit'] = $exk_unit;
                        }
                    }
                }
                $add_sample_arr['external_inspections'] = JSON($add_sample_arr['external_inspections']);
            }
            // json数据数组
            $sample_add_json_arr = $add_sample_arr['sample_add_json'];
            $add_sample_arr['sample_add_json'] = JSON($add_sample_arr['sample_add_json']);
            $add_sample_arr['customer_id'] = $id;
            $add_sample_arr['jc_yiju'] = join($add_sample_arr['jc_yiju'], '|');
            // 字符串替换 防止时分：输入错误导致采样日期错误
            if($add_sample_arr['cy_time']){
                $add_sample_arr['cy_time'] = str_replace("：",":",$add_sample_arr['cy_time']);
            }
            if (!$sample_id) {
                new_record("customer_rec", $add_sample_arr);
            } else {
                update_rec("customer_rec", $add_sample_arr, $sample_id);
                // 若在委托单中修改了[评价标准]，则同步更新cy_rec和report表中的标准id
                if ($add_sample_arr['jcyj'] && !empty($add_sample_arr)) {
                    // 是否已生成cy_rec
                    $cr_data = $DB->fetch_one_assoc("SELECT `rec_id` FROM `customer_rec` WHERE `id` = '{$sample_id}'");
                    if ($cr_data['rec_id']) {
                        $cid = $cr_data['rec_id'];
                        $jcbz_id = is_array($add_sample_arr['jcyj']) ? implode(",",$add_sample_arr['jcyj']) : $add_sample_arr['jcyj'];
                        // 更新本样品的评价标准
                        $sql = "UPDATE `cy_rec` SET `jcbz_id` = '{$jcbz_id}' WHERE `id` = '{$cid}'";
                        $DB->query($sql);
                        // 更新本样品检测报告的评价标准
                        if ($global['report']['newreport']) {
                            // 新版excel检测报告，按single_cid或summary_cids修改std_id
                            $sql = "UPDATE `assay_report` SET `std_id` = '{$jcbz_id}' WHERE `single_cid` = '{$cid}' OR FIND_IN_SET('{$cid}', `summary_cids`)";
                        } else {
                            // 常规检测报告，按cids修改jcbz_id
                            $sql = "UPDATE `report` SET `jcbz_id` = '{$jcbz_id}' WHERE FIND_IN_SET('{$cid}', `cids`)";
                        }
                        $DB->query($sql);
                    }
                }
                // 若在委托单中修改了[消毒方式]，则同步更新cy_rec
                if ($add_sample_arr['xd_fs']) {
                    // 是否已生成cy_rec
                    $cr_data = $DB->fetch_one_assoc("SELECT `rec_id` FROM `customer_rec` WHERE `id` = '{$sample_id}'");
                    if ($cr_data['rec_id']) {
                        $cid = $cr_data['rec_id'];
                        $xd_fs = $add_sample_arr['xd_fs'];
                        // 更新本样品的评价标准
                        $sql = "UPDATE `cy_rec` SET `xd_fs` = '{$xd_fs}' WHERE `id` = '{$cid}'";
                        $DB->query($sql);
                    }
                }
                // 若在委托单中修改了采样时间，则同步更新cy_rec
                if ($add_sample_arr['cy_time']) {
                    // 是否已生成cy_rec
                    $cr_data = $DB->fetch_one_assoc("SELECT `rec_id` FROM `customer_rec` WHERE `id` = '{$sample_id}'");
                    if ($cr_data['rec_id']) {
                        $cid = $cr_data['rec_id'];
                        $rec_date = date("Y-m-d",strtotime($add_sample_arr['cy_time']));
                        // 更新本样品的评价标准
                        $sql = "UPDATE `cy_rec` SET `cy_date` = '{$rec_date}' WHERE `id` = '{$cid}'";
                        $DB->query($sql);
                    }
                }
                // 若在委托单中修改了站点名称，则同步更新cy_rec和assay_order
                if ($add_sample_arr['site_name'] != $old_rec_arr[$sample_id]['site_name']) {
                    $site_name_cid = $old_rec_arr[$sample_id]['rec_id'];
                    $site_name_sid = $old_rec_arr[$sample_id]['sid'];
                    $site_name_new = $add_sample_arr['site_name'];
                    // 是否已生成cy_rec
                    if ($site_name_cid && $site_name_sid) {
                        // 若该站点关联有已签字的检测报告，则不再继续修改站点名称
                        if (!report_is_qz($site_name_cid)) {
                            $DB->query("UPDATE `cy_rec` SET `site_name`='{$site_name_new}' WHERE id='{$site_name_cid}'");
                            $DB->query("UPDATE `assay_order` SET `site_name`='{$site_name}' WHERE cid='{$site_name_cid}' AND sid>'0' AND hy_flag!='3' AND hy_flag!='-4' AND hy_flag!='-9'");
                        }
                    }
                }
                // 若在委托单中修改了站点地址，则同步更新cy_rec
                if ($add_sample_arr['site_address'] != $old_rec_arr[$sample_id]['site_address']) {
                    $site_address_cid = $old_rec_arr[$sample_id]['rec_id'];
                    $site_address_sid = $old_rec_arr[$sample_id]['sid'];
                    $site_address_new = $add_sample_arr['site_address'];
                    // 是否已生成cy_rec
                    if ($site_address_cid && $site_address_sid) {
                        // 若该站点关联有已签字的检测报告，则不再继续修改站点名称
                        if (!report_is_qz($site_address_cid)) {
                            $DB->query("UPDATE `cy_rec` SET `site_address`='{$site_address_new}' WHERE id='{$site_address_cid}'");
                        }
                    }
                }
                // 若在委托单中修改了[报告编号类型]，则同步更新cy_rec
                if ($sample_add_json_arr['report_code_type']) {
                    // 是否已生成cy_rec
                    $cr_data = $DB->fetch_one_assoc("SELECT `rec_id` FROM `customer_rec` WHERE `id` = '{$sample_id}'");
                    if ($cr_data['rec_id']) {
                        $cid = $cr_data['rec_id'];
                        $sample_cy_rec_info = $DB->fetch_one_assoc("SELECT `json` FROM `cy_rec` WHERE `id` = '{$cid}'");
                        $sample_rec_json_arr = json_decode($sample_cy_rec_info['json'],true);
                        $sample_rec_json_arr['report_code_type'] = $sample_add_json_arr['report_code_type'];
                        $sample_rec_json_str = JSON($sample_rec_json_arr);
                        // 更新本样品的报告编号类型
                        $sql = "UPDATE `cy_rec` SET `json` = '{$sample_rec_json_str}' WHERE `id` = '{$cid}'";
                        $DB->query($sql);
                    }
                }
            }
        }
        if ($sub_action == '保存') {
            return true;
        }
        $new_customer_id = $id;
    }

//创建新批次
    $kh_info = $DB->fetch_one_assoc("SELECT * FROM `customer` WHERE `id`='$new_customer_id'");
// 防止已生成的任务再次生成任务覆盖数据 todo
    if($kh_info['cyd_id']){
//        gotourl("{$rooturl}/customer_manage/customer_add.php?id={$new_customer_id}", "已生成任务，请勿重复生成！");exit;
    }
    $query = $DB->query("SELECT * FROM `customer_rec` WHERE `customer_id`='{$new_customer_id}' AND `act`='1'");
    $site_arr = array();
    $cy_date_arr = [];
    while ($row = $DB->fetch_assoc($query)) {
        $_arr = array();
        $_arr['site_name'] = trim($row['site_name']);
        $_arr['site_address'] = trim($row['site_address']);
        $_arr['water_type'] = trim($row['sample_type']) ? trim($row['sample_type']) : "1";
        // 新增站点时，按委托单中选择的评价标准或水样类型，填充在sites表中
        $_arr['jcbz_id'] = trim($row['jcyj']) ? trim($row['jcyj']) : get_jcbz_options('', $_arr['water_type'], 1);
        $_arr['vids'] = $row['vids'];
        // 开启了采样日期=委托日期，采样时间为空，取委托日期
        if(!$row['cy_time'] && $global['customer']['cyDate_eq_entrustDate']){
            $row['cy_time'] = $kh_info['entrust_date'];
            $DB->query("UPDATE `customer` SET `cy_time`='{$kh_info['entrust_date']}' WHERE `id`='{$row['id']}'");
        }
        // 不是时间的数据不会进入采样时间的数组
        if ($row['cy_time'] && strtotime($row['cy_time'])) {
            $row_cy_date = date("Y-m-d", strtotime($row['cy_time']));
            if($row_cy_date != '0000-00-00' && $row_cy_date != '1970-01-01'){
                $cy_date_arr[] =  $row_cy_date;
            }
        }
        $site_arr[$row['id']] = $_arr;
    }
    $kh_info = $DB->fetch_one_assoc("SELECT * FROM `customer` WHERE `id`='$new_customer_id'");
    $post['is_urgency'] =='1' ? $is_urgency= '1' :"0";
    $cy_date_arr = array_filter($cy_date_arr);
    $post = array();
    $post['cyd_id'] = '';
    $post['kh_id'] = $new_customer_id;
    $post['site_type'] = $global['customer']['site_type'] == '' ? '3' : $global['customer']['site_type'];
    $post['ajax_return'] = "1";
    $post['cy_flag'] = $kh_info['sample_origin'] ? "1" : "0";
// 现场检测项目（必须是采样或global开启了送样可下达现场项目的配置）
    $xc_exam_value_arr = explode("|",$kh_info['xc_exam_value']);
    if(!empty($xc_exam_value_arr) && ($post['cy_flag'] == '1' || $global['xd_cyrw']['sy_xcxm'])){
        $post['xcjc_value'] = $xc_exam_value_arr;
    }
    if($global['is_urgency']){
        $post['is_urgency']=$is_urgency;
    }
    $bgwc_date = $kh_info['report_stipulate_completion_time'];
    $post['bgwc_date'] = $bgwc_date ? $bgwc_date : '';	//报告完成时间
// 判断采样日期是否等于委托日期
    if($global['customer']['cyDate_eq_entrustDate']){
        $post['cy_riqi'] = $kh_info['entrust_date'];
        $post['end_cy_date'] = $kh_info['entrust_date'];
    }else{
        // 根据样品内填写的采样日期获取规定采样日期和结束采样日期
        if ($cy_date_arr) {
            $post['cy_riqi'] = min($cy_date_arr);
            $post['end_cy_date'] = max($cy_date_arr);
        } else {
            $post['cy_riqi'] = date('Y-m-d', time());
            $post['end_cy_date'] = date('Y-m-d', time());
        }
    }
    $client_name = $kh_info['client_name'];
    $cyrw_save_name = $client_name . date('Y_m_d', time());
//批次名称后缀序号：今日新建的第几个任务批次
    $ctime = date('Y-m-d', time());
    $query = $DB->query("select DISTINCT(`group_name`) from `site_group` where `ctime` like '$ctime%'");
    $xuhao = $DB->num_rows($query);
    $xuhao++;
    $xuhao = '_' . $xuhao;
//批次名称区分标识的定义
    $group_name_mark = date('Y_m_d', time());
    if (!empty($kh_info['code'])) {
        $group_name_mark = $kh_info['code'];
        // 有委托单编号，则按配置判断是否隐藏后缀序号
        $global['customer']['group_name_hide_xuhao'] ? ($xuhao = '') : '';
    }
    $group_name = $client_name . $group_name_mark . $xuhao;
    $post[$cyrw_save_name]['group_name'] = $group_name;
    $customer_add_json_arr = json_decode($kh_info['add_json'],true);
// 如果是检测方采样同步采样人，客户送样同步送样人
    if($post['cy_flag'] == "1"){
        $post[$cyrw_save_name]['cy_user'] = !empty($customer_add_json_arr['cy_user']) ? $customer_add_json_arr['cy_user'] : "";
    }else{
        if(!empty($customer_add_json_arr['cy_user'])){
            $post['sy_user_qz'] =  $customer_add_json_arr['cy_user'];
        }
    }
// 任务类型
    if(!empty($customer_add_json_arr['site_type'])){
        $post['site_type'] = $customer_add_json_arr['site_type'];
    }
    foreach ($site_arr as $k => $v) {
        $info = $DB->fetch_one_assoc("select * from `sites` where `site_name`='{$v['site_name']}' AND `site_address`='{$v['site_address']}' AND `water_type`='{$v['water_type']}'");
        $vids = $v['vids'];
        unset($v['vids']);
        if (empty($info['id'])) {
            // 新增站点 todo
            $v['fzx_id'] = 1;
            $v['fp_id'] = 1;
            // 判断是否有传入选择的任务类型且global内没有配置对应任务类型
            if(!empty($post['site_type']) && $global['customer']['site_type'] == ''){
                $v['site_type'] = $post['site_type'];
            }else{
                $v['site_type'] = $global['customer']['site_type'] == '' ? '3' : $global['customer']['site_type'];
            }
            $v['act'] = '1';
            // 判断是否该水样类型是否默认水源限制的值
            if($global['add_site_default_syxz'] && array_key_exists($v['water_type'],$global['add_site_default_syxz'])){
                $v['syxz'] = $global['add_site_default_syxz'][$v['water_type']];
            }
            $sid = new_record('sites', $v);
            $DB->query("UPDATE `customer_rec` SET `sid`='{$sid}' WHERE `id`={$k}");
            ### 新增的站点根据global判断是否插入站点类型归类 ###
            $site_type_id = "";
            $customer_add_sites_type = $global['customer']['add_sites_type'];
            if($customer_add_sites_type && !empty($customer_add_sites_type)){
                // 循环类型，key是站点类型id，val是水样类型id的集合
                foreach($customer_add_sites_type as $sk => $sv){
                    if($sk != 'mr' && in_array($v['water_type'],$sv)){
                        $site_type_id = $sk;
                    }
                }
                // 不存在水样类型的集合内，是否有设置默认的站点类型id
                if($site_type_id == '' && $customer_add_sites_type['mr'] != ''){
                    $site_type_id = $customer_add_sites_type['mr'];
                }
                // 站点类型id存在，且站点id存在
                if($site_type_id && $sid){
                    $site_type_old = [];
                    $site_type_old = $DB->fetch_one_assoc("SELECT * FROM `site_type_record` WHERE `sid`='{$sid}' AND `stid`='{$site_type_id}'");
                    if(empty($site_type_old)){
                        $DB->query("INSERT INTO `site_type_record` SET `sid`='{$sid}',`stid`='{$site_type_id}',`create_time`='".date("Y-m-d H:i:s",time())."'");
                    }
                }
            }
        } else {
            $sid = $info['id'];
            $DB->query("UPDATE `customer_rec` SET `sid`='{$sid}' WHERE `id`={$k}");
            // 选择已有的站点，若该站点未设置评价标准 则存入当前标准
            $DB->query("UPDATE `sites` SET `jcbz_id` = '{$v['jcbz_id']}' WHERE `id` = '{$sid}' AND (`jcbz_id` = '' OR `jcbz_id` IS NULL)");
        }
        $site_group_datas = array();
        $site_group_datas['site_id'] = $sid;
        $site_group_datas['fzx_id'] = 1;
        // 判断是否有传入选择的任务类型且global内没有配置对应任务类型
        if(!empty($post['site_type']) && $global['customer']['site_type'] == ''){
            $site_group_datas['site_type'] = $post['site_type'];
        }else{
            $site_group_datas['site_type'] = $global['customer']['site_type'] == '' ? '3' : $global['customer']['site_type'];
        }
        $site_group_datas['group_name'] = $group_name;
        $site_group_datas['cuser'] = $openid;
        $site_group_datas['assay_values'] = str_replace('|', ',', $vids);
        $site_group_datas['act'] = '1';
        $post[$cyrw_save_name]['sites'][] = $sid;
        $site_group_datas['wtdw'] = $kh_info['client_name'] ? $kh_info['client_name'] : "";
        $site_group_datas['wtdw_addr'] = $kh_info['client_address'] ? $kh_info['client_address'] : "";
        $site_group_datas['wtdw_lxr'] = $kh_info['liaison'] ? $kh_info['liaison'] : "";
        $site_group_datas['wtdw_tel'] = $kh_info['phone_number'] ? $kh_info['phone_number'] : "";
        $site_group_datas['mail_address'] = $kh_info['client_address'] ? $kh_info['client_address'] : "";
        new_record('site_group', $site_group_datas);
    }


    include_once "../huayan/ahlims.php";
    include_once "../inc/cy_func.php";
    include_once "../data_statistics/report_data_func_new.php";
    $success_info = "批任务下达成功";
// 查询所有人员
    $fzx_id = 0;
    $renarr = $cyd_arr = array();
    $rensql = $DB->query("select id,userid from users  `group`<>'0'");
    while ($ren = $DB->fetch_assoc($rensql)) {
        $renarr[$ren['userid']] = $ren['id'];
    }
    if (!$global['xd_cyrw']['sy_xcxm'] && !$post['cy_flag']) {
        $post['xcjc_value'] = '';
    }
    $cy_json_arr = [];
    $last_cy_info = $DB->fetch_one_assoc("select * from cy where id != '{$post['cyd_id']}' order by id desc");
    $last_cy_info_json = [];
    if ($last_cy_info['json']) {
        $last_cy_info_json = json_decode($last_cy_info['json'], true);
    }
    if (!empty($post['cyd_id'])) {
        $success_info = "批任务修改成功";
        $cy_rs = $cy_rec_old = $cy_rec_qckb = $cy_rec_old_zk = $cy_rec_sites = array();
        $cy_rs = $DB->fetch_one_assoc("SELECT * FROM `cy` WHERE id='" . $post['cyd_id'] . "'");
        if (!empty($cy_rs['json'])) {
            $cy_json_arr = json_decode($cy_rs['json'], true);
        }
        $site_id_str = implode(",", $post['jdrw']['sites']); //接收到的站点
        $group_site_arr = [];
        $sql_gr_value = $DB->query("SELECT site_id FROM `site_group` where fzx_id='$fzx_id' AND `group_name`='{$cy_rs['group_name']}' AND site_type='{$cy_rs['site_type']}'"); //获取批次中的所有站点
        while ($rs_gr_value = $DB->fetch_assoc($sql_gr_value)) {
            $group_site_arr[] = $rs_gr_value['site_id']; //批次中的所有站点的id
        }
        $get_sites_sql = "SELECT * FROM `sites` WHERE `id`  in({$site_id_str}) ";
        $get_sites_query = $DB->query($get_sites_sql);
        $values_sql = "";
        while ($get_sites_row = $DB->fetch_assoc($get_sites_query)) {
            $site_id = $get_sites_row['id'];
            $values_sql = ",assay_values='{$post['jdrw']['sites_value'][$site_id]}',xcpx_values='{$post['jdrw']['xcpx_value'][$site_id]}',qckb_values='{$post['jdrw']['qckb_value'][$site_id]}',xcjb_values='{$post['jdrw']['xcjb_value'][$site_id]}'";
            if ($global['enable_item_fenbao']) $values_sql .= ",xmfb_values='{$post['jdrw']['xcfb_value'][$site_id]}'";
            if (!in_array($get_sites_row['id'], $group_site_arr)) { //如果接收到的站点不在批次中就添加
                $DB->query("INSERT INTO `site_group` SET fzx_id='{$fzx_id}',site_id='{$site_id}',site_type='{$cy_rs['site_type']}',group_name='{$cy_rs['group_name']}',act='1',ctime='" . date('Y-m-d H:i:s') . "',cuser='{$u['userid']}'{$values_sql}");
            } else { //在的话就把act改为1，改项目等
                $site_group_act = $DB->fetch_one_assoc("SELECT act FROM `site_group` WHERE `site_id`='{$site_id}' AND `group_name`='{$cy_rs['group_name']}' AND site_type='{$cy_rs['site_type']}'");
                if ($site_group_act['act'] != 1) {
                    $DB->query("UPDATE `site_group` SET `act`='1' {$values_sql} WHERE `site_id`='{$site_id}' AND `group_name`='{$cy_rs['group_name']}' AND site_type='{$cy_rs['site_type']}'");
                }
            }
        }
        $post['site_type'] = $cy_rs['site_type'];
        $sql_cy_rec = $DB->query("SELECT * FROM `cy_rec` WHERE cyd_id='{$post['cyd_id']}'");
        while ($rs_cy_rec = $DB->fetch_assoc($sql_cy_rec)) {
            if ($rs_cy_rec['sid'] > 0) {
                $cy_rec_sites[] = $rs_cy_rec['sid'];
            }
            if ($rs_cy_rec['zk_flag'] >= 0) {
                if ($rs_cy_rec['zk_flag'] == 1) {
                    $cy_rec_qckb[$rs_cy_rec['kb_sid']] = $rs_cy_rec; //批次修改之前正全程序空白的信息
                } elseif ($rs_cy_rec['zk_flag'] == 11) {
                    $cy_rec_old_xcjb[$rs_cy_rec['sid']] = $rs_cy_rec; //批次修改之前现场加标站点
                } else {
                    $cy_rec_old[$rs_cy_rec['sid']] = $rs_cy_rec; //批次修改之前正常站点
                }
            } else {
                $cy_rec_old_zk[$rs_cy_rec['sid']] = $rs_cy_rec; //批次修改之前现场平行站点的信息
            }
        }
        $pay_old = $order_old = array();
        $sql_assay_pay = $DB->query("SELECT * FROM `assay_pay` WHERE cyd_id='{$post['cyd_id']}'");
        while ($rs_assay_pay = $DB->fetch_assoc($sql_assay_pay)) {
            $pay_old[$rs_assay_pay['vid']] = $rs_assay_pay; //不同方法时有可能会重复？？？
        }
        $sql_assay_order = $DB->query("SELECT * FROM `assay_order` WHERE cyd_id='{$post['cyd_id']}'");
        while ($rs_assay_order = $DB->fetch_assoc($sql_assay_order)) {
            $order_old[$rs_assay_order['cid']][$rs_assay_order['vid']] = $rs_assay_order;
        }
        //如果是修改采样任务要把之前的任务删除掉重新生成新的一批
        //$DB->query("DELETE FROM `cy` WHERE id='".$post['cyd_id']."'");
        //$DB->query("DELETE FROM `cy_rec` WHERE cyd_id='".$post['cyd_id']."'");
        $DB->query("DELETE FROM `assay_pay` WHERE cyd_id='" . $post['cyd_id'] . "' AND `is_xcjc`='1'");
        //$DB->query("DELETE FROM `assay_order` WHERE cyd_id='".$post['cyd_id']."'");
    }
    $cyd_id_list = [];
#########取出所有水样类型
    $water_type_all = array();
    $sql_water_type = $DB->query("SELECT * FROM `leixing` WHERE 1");
    while ($rs_water_type = $DB->fetch_assoc($sql_water_type)) {
        $water_type_all[$rs_water_type['id']] = $rs_water_type['parent_id'];
        $water_type_name_arr[$rs_water_type['id']] = $rs_water_type['lname'];
    }
#########取出现场平行项目
    $xcpx_value = $DB->fetch_one_assoc("SELECT module_value1 FROM `n_set` WHERE fzx_id='$fzx_id' AND module_name='xcpx_value' AND module_value2='{$post['site_type']}' ORDER BY id DESC LIMIT 1");
    $xcpx_value_arr = @explode(',', $xcpx_value['module_value1']);
#########取出全程序空白项目
    $qckb_value = $DB->fetch_one_assoc("select module_value1 from `n_set` where fzx_id='$fzx_id' and module_name='qckb_value' and module_value2='{$post['site_type']}' order by id DESC limit 1");
    $qckb_value_arr = @explode(',', $qckb_value['module_value1']);
    $water_type_sql = $DB->query("SELECT * FROM `leixing` WHERE 1");
    while ($rs_water_type = $DB->fetch_assoc($water_type_sql)) {
        $water_type_data[$rs_water_type['id']] = $rs_water_type['lname'];
    }
//获取站点有没有多个垂线和层面
    $sql_site_line_vertical = array();
    $sql_site_line_vertical = $DB->query("SELECT * FROM `sites` WHERE (fzx_id='$fzx_id' OR fp_id='$fzx_id') AND (`site_code`!='' OR `site_code` is not NULL)  and act='1' ORDER BY tjcs,site_name");
    while ($rs_site_line_vertical = $DB->fetch_assoc($sql_site_line_vertical)) {
        //奇怪，sql里面的为空限制不管用。这里只能再加一道关
        if ($rs_site_line_vertical['site_code'] != '') {
            $site_line_vertical[$rs_site_line_vertical['site_code']][$rs_site_line_vertical['water_type']][] = 1; //$rs_site_line_vertical['site_code'];
        }
    }
    $no_xmmb_rq = true;  //项目模板关联采样容器 现只有郑州中心使用
    if (!empty($global['rq_value_relate'])) { //是否通过项目模板获取容器
        // 查询所有项目模板
        $xmmb_query = $DB->query("select * from `n_set` where `module_name`='xmmb' and (`fzx_id` in('','0','{$fzx_id}') OR isNULL(`fzx_id`)) and `module_value3`='1' and `id` in(" . implode(',', array_keys($global['rq_value_relate'])) . ") ");
        $xmmb = [];
        while ($mb_rs = $DB->fetch_assoc($xmmb_query)) {
            $mb_rs_tmp = explode(',', $mb_rs['module_value1']);
            sort($mb_rs_tmp);
            $xmmb[$mb_rs['id']] = implode(',', $mb_rs_tmp);
        }
        // 查询所有容器
        $rq_sql = "SELECT * FROM `rq_value` WHERE vid!='' AND fzx_id='" . $fzx_id . "'  ORDER BY id";
        $rq_query = $DB->query($rq_sql);
        $rq_all_arr = [];
        while ($rq_rs = $DB->fetch_assoc($rq_query)) {
            $rq_all_arr[$rq_rs['id']] = $rq_rs;
        }
    }
//判断是否需要验收模块
    if ($yanshou_peizhi == '有验收') {
        $ys_status = '4';
    } elseif ($yanshou_peizhi == '没有验收') {
        $ys_status = '3';
    } else {
        $ys_status = '3';
    }
    $all_xm_list = get_av_data();
    $xdcy_nset_query = $DB->fetch_one_assoc("SELECT * FROM n_set WHERE module_name='xdcy'");
    $xdcy_nset = json_decode($xdcy_nset_query['module_value1'], true);
#####循环传过来的数组，将每个批次的数据插入cy表
    $xy_i = 0; //下达采样任务成功的批次数
    foreach ($post as $key => $value) {
        //区分出每个批次的信息
        $cy_info = $xcpx_sites = $pay_vids = array();
        $all_assay_values = $water_type_arr = $xc_exam_arr = $xc_water_type = array();
        if (is_array($value) && @array_key_exists('sites', $value)) {
            //修改采样任务时，先将去掉的站点的cy_rec表的记录删除掉
            if (!empty($post['cyd_id'])) {
                $old_sites = array_diff($cy_rec_sites, $value['sites']);
                $old_sites_str = implode(',', $old_sites);
                if ($old_sites_str != '') {
                    $DB->query("DELETE FROM `cy_rec` WHERE cyd_id='{$post['cyd_id']}' and (sid in ($old_sites_str) OR `kb_sid` in ('{$old_sites_str}'))");
                    $DB->query("DELETE FROM `assay_order`	WHERE cyd_id='{$post['cyd_id']}' and sid in ($old_sites_str)");
                }
            }
            ########生成记录到cy表
            $group_name_str = $value['group_name'];
            if (!empty($value['cy_user'])) {
                $tmp_user = explode(',', $value['cy_user']);
                $cy_info['cy_user'] = $tmp_user[0];
                $cy_info['cy_user2'] = $tmp_user[1];
                $cy_info['cy_users'] = $value['cy_user'];
            }
            $cy_info['site_type'] = $post['site_type']; //任务性质
            $cy_info['cy_flag'] = $post['cy_flag']; //是否是委托检测
            $cy_info['fzx_id'] = $fzx_id; //分中心id
            $cy_info['group_name'] = ($post['group_name'] != '') ? $post['group_name'] : $group_name_str; //批名
            $cy_info['cy_user'] = ($post['cy_flag'] == '1') ? $cy_info['cy_user'] : "委托方"; //采样人1
            $cy_info['cy_user2'] = ($post['cy_flag'] == '1') ? $cy_info['cy_user2'] : ""; //采样人2
            $cy_info['cy_users'] = ($post['cy_flag'] == '1') ? $cy_info['cy_users'] : "委托方"; //采样人2
            $cy_info['status'] = (($post['cy_flag'] == '1') && (!$global['xd_cyrw']['arrive_yp_ys'])) ? "0" : $ys_status; //批次样品状态,如果是委托方送样，那状态直接到“样品接收” 郑州常规任务也改成到“样品接收”
            $cy_info['cy_date'] = $post['cy_riqi']; //采样日期
            $cy_info['end_cy_date'] = (empty($post['end_cy_date']) || $post['end_cy_date'] == '0000-00-00') ? $post['cy_riqi'] : $post['end_cy_date']; //采样日期
            $cy_info['create_date'] = date('Y-m-d'); //创建日期
            $cy_info['create_time'] = date('H:i:s'); //创建时间
            $cy_info['create_user'] = $u['userid']; //创建人
            $cy_info['sites'] = implode(",", $value['sites']); //站点集合
            $cy_info['xc_exam_value'] = @implode(",", $post['xcjc_value']); //现场检测项目集合
            if ($global['huanjing_show'] && !empty($post['xc_huanjing_value'])) {
                $cy_info['xc_huanjing'] = @implode(",", $post['xc_huanjing_value']);//环境参数集合
            }
            if ($global['cy_show_bgwc_date']) {
                $cy_info['bgwc_date'] = $post['bgwc_date'] ? $post['bgwc_date'] : '';    //报告完成日期
            }
            if ($global['xd_cyrw_create_snkb']) {
                $cy_info['snkb'] = (isset($value['snkb']) && $value['snkb'] == 'yes') ? 1 : 0; // 是否勾选批次的 检测室内空白
            } else {
                $cy_info['snkb'] = ($xdcy_nset['create_snkb'] == 'yes') ? 1 : 0; //是否同时检测室内空白
            }
            // 委托单位信息
            $sg_sql = "SELECT * FROM `site_group` WHERE `group_name` = '{$cy_info['group_name']}' ORDER BY `id` DESC LIMIT 1";
            $sg_row = $DB->fetch_one_assoc($sg_sql);
            $cy_info['cy_dept'] = $sg_row['wtdw'] ? $sg_row['wtdw'] : '';
            $cy_info['cy_dept_address'] = $sg_row['wtdw_addr'] ? $sg_row['wtdw_addr'] : '';
            $cy_info['wtdw_lxr'] = $sg_row['wtdw_lxr'] ? $sg_row['wtdw_lxr'] : '';
            $cy_info['wtdw_tel'] = $sg_row['wtdw_tel'] ? $sg_row['wtdw_tel'] : '';
            $cy_info['wtdw_sjdw'] = $sg_row['wtdw_sjdw'] ? $sg_row['wtdw_sjdw'] : '';
            $cy_json_arr['sample_desc'] = $sg_row['sample_desc'] ? $sg_row['sample_desc'] : '';  //样品说明
            $cy_json_arr['hyd_user_group'] = $last_cy_info_json['hyd_user_group'];  // 化验单人员分组
            if ($global['is_urgency']) {
                if ($post['is_urgency'] == '1') {
                    $cy_json_arr['message'] = '1';
                    $cy_json_arr['message_user'] = $u['userid'];
                    $cy_json_arr['message_date'] = time();
                }
            }
            $cy_info['json'] = JSON($cy_json_arr);
            // 委托协议下达任务选择了送样且填写了送样人将送样人保存到任务里
            if ($post['cy_flag'] == "0" && !empty($post['sy_user_qz']) && $post['kh_id']) {
                $cy_info['sy_user_qz'] = $post['sy_user_qz'];
                $cy_info['sy_user_qz_date'] = date("Y-m-d");
            }
            //计算样品数量
            $cy_info['yp_count'] = count($value['sites']);
            if (!empty($value['xcpx'])) {
                $cy_info['yp_count'] = $cy_info['yp_count'] + count($value['xcpx']);
            }
            if (isset($value['qckb'])) {
                $cy_info['yp_count'] = $cy_info['yp_count'] + count($value['qckb']);
            }
            //现场检测项目数组
            if (!empty($post['xcjc_value'])) {
                $xc_exam_arr = $post['xcjc_value'];
            }
            if (empty($post['cyd_id'])) {
                //拼接个性函数名称
                if (!empty($dw_biaozhi)) {
                    $func_name_cyd_bh = $dw_biaozhi . '_new_cyd_bh';
                }
                if (function_exists($func_name_cyd_bh)) {
                    $cy_info["cyd_bh"] = $func_name_cyd_bh($cy_info['site_type'], $cy_info['cy_date'], $cy_info['cy_flag']); //个性生成采样单编号的函数
                } else {
                    $cy_info["cyd_bh"] = new_cyd_bh($cy_info['site_type'], $cy_info['cy_date']); //生成采样单编号,函数在cy_func.php中
                }
                //查询同一任务类型上一次的备注并更新到这次的任务中

                $cy_info['jc_dept'] = $global['jc_dept'] ? $global['jc_dept'] : ($fzx_rs['hub_name'] ? $fzx_rs['hub_name'] : $old_cy_rs['jc_dept']);
                $cy_info['cy_dept'] = $global['cy_dept'] ? $global['cy_dept'] : $cy_info['cy_dept'];
                //将数据插入cy表，函数在function.php中
                $cyd_id = new_record('cy', $cy_info);
                if (!$first_cyd_id) {
                    $first_cyd_id = $cyd_id;
                }
                if (!empty($cyd_id)) {
                    $cyd_arr[] = $cyd_id;
                }
                if (!$cyd_id) {
                    die("生成采样单失败!");
                }
            } else {
                ########修改采样单的时候只更新不生成
                //去除掉不需要更新的字段
                unset($cy_info["cyd_bh"]);
                unset($cy_info["status"]);
                unset($cy_info["create_date"]);
                unset($cy_info["create_time"]);
                unset($cy_info["create_user"]);
                $cy_info['cy_dept'] = $cy_rs['cy_dept'];
                $sum_cyd = update_rec('cy', $cy_info, $post['cyd_id']);
                $cyd_id = $post['cyd_id'];
                if (!$first_cyd_id) {
                    $first_cyd_id = $cyd_id;
                }
                if (!empty($cyd_id)) {
                    $cyd_arr[] = $cyd_id;
                }
            }
            #########生成记录到cy_rec表
            $xmfb_sites = [];
            $xcpx_sites = $value['xcpx']; //检测现场平行的站点
            $xcjb_sites = $value['xcjb']; //检测现场加标的站点
            $qckb_sites = $value['qckb']; //检测qckb的站点
            if (isset($value['xmfb']) && !empty($value['xmfb'])) {
                $xmfb_sites = $value['xmfb']; // 检测项目分包的站点
            }
            $where_sites = '';
            if ($key != 'jdrw') {
                $where_sites .= "AND sg.group_name = '{$cy_info['group_name']}'";
                $where_sites2 = "AND sg.act='1' and sg.`site_type`='{$cy_info['site_type']}'";
                $where_sites3 = "sg.fzx_id='$fzx_id'";
                $order_sites = "sg.site_sort,";
            } else {
                $where_sites3 = "(s.fzx_id='$fzx_id' or s.fp_id='$fzx_id')";
                $order_sites = "";
            }
            //可以用gr_id
            if (!empty($value['gr_ids'])) {
                $where_sites .= "AND sg.id in (" . implode(",", $value['gr_ids']) . ")";
            }
            // 解决修改时排序变化问题
            if (!empty($post['cyd_id'])) {
                $where_sites .= "AND sg.group_name = '{$post['old_group_name']}'";
            } else {
                if (empty($post['jdrw'])) {
                    $where_sites .= "AND sg.group_name = '{$cy_info['group_name']}'";
                }
            }
            if ($global['huanjing_show']) {
                $huanjing_where = "sg.milieu_values,sg.xcpx_milieu_values,sg.qckb_milieu_values,";
            }
            if ($global['site_info_wtdw']) {
                $sql_field = "s.json as site_json,";
            }
            $fb_where = '';
            if ($global['enable_item_fenbao']) {
                $fb_where = "sg.xmfb_values,";
            }
            $sql_siteArr = $DB->query("
				SELECT
					s.id AS sid,s.site_name,s.water_type,s.jcbz_id,s.river_name,s.water_system,s.site_code,s.fix_bar_code,s.site_address,s.site_line,s.site_vertical,s.jingdu,s.weidu,s.wtdw,{$sql_field}
					sg.id,sg.assay_values,sg.xcpx_values,sg.qckb_values,sg.xcjb_values,sg.site_task_ids,{$huanjing_where}{$fb_where}
					curdate() AS create_date
				FROM `site_group` AS sg
				RIGHT JOIN sites AS s ON s.id = sg.site_id
				WHERE $where_sites3 $where_sites AND s.`id` IN({$cy_info['sites']}) $where_sites2
				GROUP BY s.`id`
				ORDER BY {$order_sites} field(s.id,{$cy_info['sites']})
		");
            if ($DB->num_rows($sql_siteArr) <= 0) {
                $where_sites = "AND sg.group_name like '%{$cy_info['group_name']}%'";
                $sql_siteArr = $DB->query("
				SELECT
					s.id AS sid,s.site_name,s.water_type,s.jcbz_id,s.river_name,s.water_system,s.site_code,s.fix_bar_code,s.site_address,s.site_line,s.site_vertical,s.jingdu,s.weidu,{$sql_field}
					sg.id,sg.assay_values,sg.xcpx_values,sg.qckb_values,sg.xcjb_values,sg.site_task_ids,{$huanjing_where} {$fb_where}
					curdate() AS create_date
				FROM `site_group` AS sg
				RIGHT JOIN sites AS s ON s.id = sg.site_id
				WHERE $where_sites3 $where_sites AND s.`id` IN({$cy_info['sites']}) $where_sites2
				GROUP BY s.`id`
				ORDER BY {$order_sites} field(s.id,{$cy_info['sites']})
			");
            }
            $px = 0; //rec表排序
            $xcpx_px = 1;
            $qxkb_px = 1;
            while ($rs_siteArr = $DB->fetch_assoc($sql_siteArr)) {
                $add_xcpx_before_qxkb_flag = 0;
                if ($global['huanjing_show']) {
                    //监督任务的现场环境项目可能是由页面设置的，如果设置过了，这里用设置的项目，不用数据库里存储的
                    if (!empty($value['milieu_values'][$rs_siteArr['sid']])) {
                        $rs_siteArr['milieu_values'] = $value['milieu_values'][$rs_siteArr['sid']];
                    }
                    if (!empty($value['xcpx_milieu_values'][$rs_siteArr['sid']])) {
                        $rs_siteArr['xcpx_milieu_values'] = $value['xcpx_milieu_values'][$rs_siteArr['sid']];
                    }
                    if (!empty($value['qckb_milieu_values'][$rs_siteArr['sid']])) {
                        $rs_siteArr['qckb_milieu_values'] = $value['qckb_milieu_values'][$rs_siteArr['sid']];
                    }
                }
                //监督任务的项目可能是由页面设置的，如果设置过了，这里用设置的项目，不用数据库里存储的
                if (!empty($value['sites_value'][$rs_siteArr['sid']])) {
                    $rs_siteArr['assay_values'] = $value['sites_value'][$rs_siteArr['sid']];
                }
                // 监督任务的分包项目可能是由页面设置的，这里用设置的项目
                if (!empty($value['xcfb_value'][$rs_siteArr['sid']])) {
                    $rs_siteArr['xmfb_values'] = $value['xcfb_value'][$rs_siteArr['sid']];
                }
                if (array_key_exists($rs_siteArr['sid'], $value['xcpx_value'])) {
                    //echo "没有设置{$rs_siteArr['site_name']}的现场平行项目！";
                    $rs_siteArr['xcpx_values'] = $value['xcpx_value'][$rs_siteArr['sid']];
                }
                if (array_key_exists($rs_siteArr['sid'], $value['xcjb_value'])) {
                    //echo "没有设置{$rs_siteArr['site_name']}的现场平行项目！";
                    $rs_siteArr['xcjb_values'] = $value['xcjb_value'][$rs_siteArr['sid']];
                }
                if (array_key_exists($rs_siteArr['sid'], $value['qckb_value'])) {
                    //echo "没有设置{$rs_siteArr['site_name']}的全程空白项目！";
                    $rs_siteArr['qckb_values'] = $value['qckb_value'][$rs_siteArr['sid']];
                }
                if ($global['enable_item_fenbao']) {
                    $rs_siteArr['fb_item'] = '';
                    if ((in_array($rs_siteArr['sid'], $xmfb_sites) || in_array($rs_siteArr['sid'], $post['jdrw']['xcfb']))) { //下达任务/修改任务 分包的站点
                        $rs_siteArr['assay_values'] = implode(",", array_diff(explode(',', $rs_siteArr['assay_values']), explode(',', $rs_siteArr['xmfb_values'])));
                        $rs_siteArr['xcpx_values'] = implode(",", array_diff(explode(',', $rs_siteArr['xcpx_values']), explode(',', $rs_siteArr['xmfb_values'])));
                        $rs_siteArr['xcjb_values'] = implode(",", array_diff(explode(',', $rs_siteArr['xcjb_values']), explode(',', $rs_siteArr['xmfb_values'])));
                        $rs_siteArr['qckb_values'] = implode(",", array_diff(explode(',', $rs_siteArr['qckb_values']), explode(',', $rs_siteArr['xmfb_values'])));
                        $rs_siteArr['fb_item'] = $rs_siteArr['xmfb_values'];
                    }
                    unset($rs_siteArr['xmfb_values']);
                }

                $gr_id = $rs_siteArr['id'];
                $rs_siteArr['gr_id'] = $rs_siteArr['id'];
                unset($rs_siteArr['id']);
                $key_code = array_search($rs_siteArr['site_name'], $sitename_arr);
                //判断相同站码但水样类型不同的站点
                $line_vertical = '';
                if (count($site_line_vertical[$key_code]) > 1) {
                    $line_vertical .= "(" . $water_type_data[$rs_siteArr['water_type']] . ")";
                }
                //判断出该站点的垂线和层面
                if (count($site_line_vertical[$key_code][$rs_siteArr['water_type']]) > 1) {
                    $str_site_line = $global['site_line'][$rs_siteArr['site_line']];
                    $str_site_vertical = $global['site_vertical'][$rs_siteArr['site_vertical']];
                    if ($rs_siteArr['site_type'] > 1) {
                        //非常规任务的站点不让显示层面垂线
                        $line_vertical .= "";
                    } else {
                        $line_vertical .= "(" . $str_site_line . $str_site_vertical . ")";
                    }
                }
                // 之前的断面未生效，这里判断该站点的断面
                if (count($site_line_vertical[$rs_siteArr['site_code']][$rs_siteArr['water_type']]) > 1 && $global['rec_site_line']) {
                    $line_vertical = '';
                    $str_site_line = $global['site_line'][$rs_siteArr['site_line']];
                    $str_site_vertical = $global['site_vertical'][$rs_siteArr['site_vertical']];
                    $line_vertical .= "(" . $str_site_line . $str_site_vertical . ")";
                }
                $rs_siteArr['site_name'] .= $line_vertical;
                $site_json = !empty($rs_siteArr['site_json']) ? json_decode($rs_siteArr['site_json'], true) : '';
                $site_wtdw = $rs_siteArr['wtdw'] ?? '';
                $site_wtdw_lxr = $site_json['wtdw_lxr'] ?? '';
                $site_wtdw_phone = $site_json['wtdw_phone'] ?? '';
                unset($rs_siteArr['site_code']);
                unset($rs_siteArr['site_line']);
                unset($rs_siteArr['site_vertical']);
                unset($rs_siteArr['jingdu']);
                unset($rs_siteArr['weidu']);
                unset($rs_siteArr['wtdw']);
                unset($rs_siteArr['site_json']);
                $fix_bar_code = $rs_siteArr['fix_bar_code']; //记录下固定的样品编号
                unset($rs_siteArr['fix_bar_code']);
                $cy_rec_info = array();
                $xcpx_values = $rs_siteArr['xcpx_values']; //现场平行样检测的项目
                $qckb_values = $rs_siteArr['qckb_values']; //全程空白检测的项目
                $xcjb_values = $rs_siteArr['xcjb_values']; //现场加标检测的项目
                if ($global['huanjing_show']) {
                    $xcpx_milieu_values = $rs_siteArr['xcpx_milieu_values'];//现场平行样检测的项目
                    $qckb_milieu_values = $rs_siteArr['qckb_milieu_values'];//全程空白检测的项目
                    unset($rs_siteArr['xcpx_milieu_values']);//向rec表添加数据的时候，不需要这个字段
                    unset($rs_siteArr['qckb_milieu_values']);//向rec表添加数据的时候，不需要这个字段
                }
                unset($rs_siteArr['xcpx_values']); //向rec表添加数据的时候，不需要这个字段
                unset($rs_siteArr['qckb_values']); //向rec表添加数据的时候，不需要这个字段
                unset($rs_siteArr['xcjb_values']); //向rec表添加数据的时候，不需要这个字段
                $cy_rec_info = $rs_siteArr; //站点的基本信息
                $rs_site_name = $cy_rec_info['site_name'];
                $cy_rec_info['cyd_id'] = $cyd_id; //采样单id
                //修改检测任务 排序不改变
                $cy_rec_info['px'] = ++$px; //rec表排序
                //委托任务时，将采样日期直接写入cy_rec表，方便后期数据获取
                if ($cy_info['cy_flag'] != '1') {
                    $cy_rec_info['cy_date'] = $cy_info['cy_date'];
                }
                $cy_rec_info['zk_flag'] = @in_array($rs_siteArr['sid'], $xcpx_sites) ? 5 : 0; //质控标识
                $qckb_flag = @in_array($rs_siteArr['sid'], $qckb_sites) ? 1 : 0; //需要添加全程空白的标志
                //根据小类查出大类
                $fater_water = $cy_rec_info['water_type'];
                // if (!array_key_exists($fater_water, $global['bar_code']['water_type'])) {
                // 	if ($water_type_all[$fater_water] != '0') {
                // 		$fater_water = $water_type_all[$fater_water];
                // 	} else {
                // 		echo "<script>alert('请联系管理员：水样类型$fater_water没有配置样品编号');</script>";
                // 	}
                // }
                $cy_rec_info['bar_code'] = ''; //生成样品编号,函数在cy_func.php中
                $old_bar_code = $cy_rec_info['bar_code']; //记录下原样的样品编号
                //统计出一共有集中 水样类型并存到数组中
                if (!in_array($rs_siteArr['water_type'], $water_type_arr)) {
                    $water_type_arr[] = $rs_siteArr['water_type'];
                }
                //将默认采样容器瓶数写入采样rec表的json字段
                $rq_sql = "SELECT * FROM `rq_value` WHERE vid!='' AND fzx_id='" . $fzx_id . "'  AND (find_in_set('0', water_type) or find_in_set('{$rs_siteArr['water_type']}', water_type))  ORDER BY id";
                $rq_query = $DB->query($rq_sql);
                $tmp_rec_json = array();
                if (!empty($cy_rec_old[$cy_rec_info['sid']]['json'])) {
                    $tmp_rec_json = json_decode($cy_rec_old[$cy_rec_info['sid']]['json'], true);
                    if ($tmp_rec_json['rq']) {
                        unset($tmp_rec_json['rq']); //清除历史容器信息
                    }
                }
                // 昆明 采样记录表 体积要不为0。站点项目和现场检测，取消取差集
                if ($global['cyrw']['xc_yq']) {
                    $avarr = explode(',', $cy_rec_info['assay_values']);
                } else {
                    $avarr = array_diff(explode(',', $cy_rec_info['assay_values']), $xc_exam_arr);
                }
                $assay_values_arr = explode(',', $cy_rec_info['assay_values']); //此站点所测的项目（数组）
                //获得一批中所有的项目(后面取交集用)
                $all_assay_values = array_unique(array_merge($all_assay_values, $assay_values_arr));
                $no_xmmb_rq = true;
                if (!empty($global['rq_value_relate'])) {
                    sort($assay_values_arr);
                    $cy_rec_info_sort_assay_values_str = implode(',', $assay_values_arr);
                    // 查询站点项目是否属于项目模板，属于则获取固定的采样容器及数量
                    if (array_search($cy_rec_info_sort_assay_values_str, $xmmb) !== false) {
                        $xmmb_id = array_search($cy_rec_info_sort_assay_values_str, $xmmb);
                        $rq_id_arr = [];
                        $rq_id_arr = array_keys($global['rq_value_relate'][$xmmb_id]);
                        foreach ($rq_id_arr as $_rq_id) {
                            $tmp_rec_json['rq'][$_rq_id] = $global['rq_value_relate'][$xmmb_id][$_rq_id];
                        }
                        $no_xmmb_rq = false;
                    }
                }
                if ($no_xmmb_rq) {
                    while ($rq_rs = $DB->fetch_assoc($rq_query)) {
                        $rq_value = explode(',', $rq_rs['vid']);
                        $rq_conditions = json_decode($rq_rs['conditions'], true);
                        if ($global['rq_site_type']) {
                            // #10859  #11395
                            // $post["kh_id"] 客户管理-新建委托单里的 委托单位 ,有值则是从委托单下的任务
                            // ['task_type']['operate']  1 都使用，2 采样任务下达使用，3 客户管理委托单使用  从'采样计划下达' 下达任务, operate值 不为3使用该容器 ；从委托单里下达任务，operate值 不为2使用该容器
                            // ['site_type']  任务类型 ，$global['site_type']同步 。下的任务类型和 容器 设置的任务类型一致才使用该容器，
                            if (((!$post["kh_id"] && $rq_conditions['task_type']['operate'] == '3') || (!in_array($post['site_type'], $rq_conditions['site_type']) && !empty($rq_conditions['site_type']))) || ($post["kh_id"] && $rq_conditions['task_type']['operate'] == '2')) {
                                continue;
                            }
                        }
                        if (array_intersect($avarr, $rq_value)) {
                            $mr_shu = empty($rq_conditions) ? $rq_rs['mr_shu'] : rq_conditions_result($rq_conditions, $avarr, $rq_rs);
                            if ($mr_shu !== false) {
                                $tmp_rec_json['rq'][$rq_rs['id']] = $mr_shu;
                            }
                        }
                    }
                }
                if ($global['is_sj_client']) {
                    $wtdw = $DB->fetch_one_assoc("select wtdw from site_group where group_name = '$group_name_str' and act = '1'");
                    $wtdw = implode('', $wtdw);
                    $cy_rec_info['sj_client'] = $wtdw;
                }
                if ($global['report']['get_site_wtdw_info']) {
                    $tmp_rec_json['wtdw']['name'] = $site_wtdw;
                    $tmp_rec_json['wtdw']['lxr'] = $site_wtdw_lxr;
                    $tmp_rec_json['wtdw']['phone'] = $site_wtdw_phone;
                }
                $cy_rec_info['json'] = JSON($tmp_rec_json);
                // 若站点未设置评价标准，则按水样类型查询默认评价标准
                if (!empty($cy_rec_old[$cy_rec_info['sid']]['jcbz_id'])) {
                    $cy_rec_info['jcbz_id'] = $cy_rec_old[$cy_rec_info['sid']]['jcbz_id'];    //获取原数据的jcbz_id
                }
                $cy_rec_info['jcbz_id'] ? '' : $cy_rec_info['jcbz_id'] = get_jcbz_options('', $cy_rec_info['water_type'], 1);
                //采样容器存储结束
                if (empty($post['cyd_id']) || empty($cy_rec_old[$cy_rec_info['sid']]['id'])) {
                    $cid = new_record('cy_rec', $cy_rec_info); //将数据插入cy_rec表，函数在function.php中
                } else {
                    $cid = $cy_rec_old[$cy_rec_info['sid']]['id'];
                    //unset($cy_rec_info['bar_code']);
                    $cy_rec_info['bar_code'] = $cy_rec_old[$cy_rec_info['sid']]['bar_code'];
                    $update_cy_rec_info = $cy_rec_info;
                    unset($update_cy_rec_info['create_date']);
                    unset($update_cy_rec_info['create_man']);
                    update_rec('cy_rec', $update_cy_rec_info, $cid);
                }
                ##########全程序空白样的处理
                $cy_rec_qckb_info = array();
                $qckb_zk = '';
                if ($qckb_flag == 1) {
                    $yuan_cid = $cid; //原样的cid
                    $cy_rec_qckb_info = $cy_rec_info; //避免全程空白修改了原样的order表信息
                    // 全程空白是否需排在现场平行之后
                    if ($global['xdcw_qckb_after_xcpx']) {
                        if ($global['xdcw_xcpx_last']) {
                            // 现场平行样品编号放最后
                            $all_px = count($value['sites']) + count($value['xcjb']) + count($value['xcpx']); // 除现场平行外其它样品数量
                            $cy_rec_qckb_info['px'] = $all_px + $qxkb_px;
                            $qxkb_px++;
                        } else {
                            if (in_array($cy_rec_info['sid'], $xcpx_sites)) {
                                $cy_rec_qckb_info['px'] = $px + 2; //rec排序
                                $add_xcpx_before_qxkb_flag = 1;
                            } else {
                                $cy_rec_qckb_info['px'] = ++$px; //rec排序
                            }
                        }
                    } else {
                        $cy_rec_qckb_info['px'] = ++$px; //rec排序
                    }
                    $qckb_bar_code = $cy_rec_qckb_info['bar_code']; //记录全程空白原样的样品编号，后面现场项目插入order表用
                    $qckb_zk = 1; //主要给样品编号编号时使用的
                    // $cy_rec_qckb_info['bar_code']= new_bar_code($cy_info['site_type'],$fater_water,$cy_info['cy_date'],$fix_bar_code);//qckb样的新样品编号
                    $cy_rec_qckb_info['bar_code'] = ''; //qckb样的新样品编号
                    $qckb_zk = '';
                    $cy_rec_qckb_info['zk_flag'] = '1'; //qckb质控标识
                    $cy_rec_qckb_info['site_name'] .= '（全程空白）'; //qckb站点名称
                    $qckb_assay_values = explode(",", $rs_siteArr['assay_values']);
                    $cy_rec_qckb_info['kb_sid'] = $cy_rec_qckb_info['sid'];
                    $cy_rec_qckb_info['sid'] = 0;
                    $cy_rec_qckb_info['river_name'] = '质控';
                    // $cy_rec_qckb_info['water_type'] = '0';
                    if (empty($qckb_values)) {
                        $cy_rec_qckb_info['assay_values'] = implode(",", array_diff($qckb_assay_values, $qckb_value_arr));
                    } else {
                        $qckb_values_arr = explode(",", $qckb_values);
                        $cy_rec_qckb_info['assay_values'] = implode(",", array_intersect($qckb_values_arr, $qckb_assay_values));
                    }
                    if ($global['huanjing_show']) {
                        if (empty($qckb_milieu_values)) {
                            $cy_rec_qckb_info['milieu_values'] = $rs_siteArr['milieu_values'];
                        } else {
                            $qckb_milieu_values_arr = explode(",", $qckb_milieu_values);
                            $cy_rec_qckb_info['milieu_values'] = implode(",", array_intersect($qckb_milieu_values_arr, explode(',', $rs_siteArr['milieu_values'])));
                        }
                    }
                    //将默认采样容器瓶数写入采样rec表的json字段
                    // $rq_sql = "SELECT * FROM `rq_value` WHERE vid!='' AND fzx_id='" . $fzx_id . "' AND `water_type` IN(0,{$cy_rec_qckb_info['water_type']}) ORDER BY id";
                    $rq_sql = "SELECT * FROM `rq_value` WHERE vid!='' AND fzx_id='" . $fzx_id . "'  AND (find_in_set('0', water_type) or find_in_set('{$cy_rec_qckb_info['water_type']}', water_type))  ORDER BY id";
                    $rq_query = $DB->query($rq_sql);
                    $tmp_rec_json = array();
                    if (!empty($cy_rec_qckb[$cy_rec_info['sid']]['json'])) {
                        $tmp_rec_json = json_decode($cy_rec_qckb[$cy_rec_info['sid']]['json'], true);
                        if ($tmp_rec_json['rq']) {
                            unset($tmp_rec_json['rq']); //清除历史容器信息
                        }
                    }
                    if ($global['cyrw']['xc_yq']) {
                        $avarr = explode(',', $cy_rec_qckb_info['assay_values']);
                    } else {
                        $avarr = array_diff(explode(',', $cy_rec_qckb_info['assay_values']), $xc_exam_arr);
                    }
                    $no_xmmb_rq = true;
                    if (!empty($global['rq_value_relate'])) {
                        sort($assay_values_arr);
                        $cy_rec_info_sort_assay_values_str = implode(',', $assay_values_arr);
                        // 查询站点项目是否属于项目模板，属于则获取固定的采样容器及数量
                        if (array_search($cy_rec_info_sort_assay_values_str, $xmmb) !== false) {
                            $xmmb_id = array_search($cy_rec_info_sort_assay_values_str, $xmmb);
                            $rq_id_arr = [];
                            $rq_id_arr = array_keys($global['rq_value_relate'][$xmmb_id]);
                            foreach ($rq_id_arr as $_rq_id) {
                                $tmp_rec_json['rq'][$_rq_id] = $global['rq_value_relate'][$xmmb_id][$_rq_id];
                            }
                            $no_xmmb_rq = false;
                        }
                    }
                    if ($no_xmmb_rq) {
                        while ($rq_rs = $DB->fetch_assoc($rq_query)) {
                            $rq_value = explode(',', $rq_rs['vid']);
                            $rq_conditions = json_decode($rq_rs['conditions'], true);
                            if ($global['rq_site_type']) {
                                if (((!$post["kh_id"] && $rq_conditions['task_type']['operate'] == '3') || (!in_array($post['site_type'], $rq_conditions['site_type']) && !empty($rq_conditions['site_type']))) || ($post["kh_id"] && $rq_conditions['task_type']['operate'] == '2')) {
                                    continue;
                                }
                            }
                            if (array_intersect($avarr, $rq_value)) {
                                $mr_shu = empty($rq_conditions) ? $rq_rs['mr_shu'] : rq_conditions_result($rq_conditions, $avarr, $rq_rs);
                                if ($mr_shu !== false) {
                                    $tmp_rec_json['rq'][$rq_rs['id']] = $mr_shu;
                                }
                            }
                        }
                    }
                    $cy_rec_qckb_info['json'] = JSON($tmp_rec_json);
                    //采样容器存储结束
                    if (empty($post['cyd_id']) || empty($cy_rec_qckb[$cy_rec_info['sid']]['id'])) {
                        $qckb_cid = new_record('cy_rec', $cy_rec_qckb_info); //不能使用$cid,不然会和现场平行冲突
                    } else {
                        $qckb_cid = $cy_rec_qckb[$cy_rec_info['sid']]['id']; //不能使用$cid,不然会和现场平行冲突
                        $cy_rec_qckb_info['bar_code'] = $cy_rec_qckb[$cy_rec_info['sid']]['bar_code'];
                        $cy_rec_qckb_info['jcbz_id'] = $cy_rec_qckb[$cy_rec_info['sid']]['jcbz_id'];
                        $update_cy_rec_info = $cy_rec_qckb_info;
                        unset($update_cy_rec_info['create_date']);
                        unset($update_cy_rec_info['create_man']);
                        update_rec('cy_rec', $update_cy_rec_info, $qckb_cid);
                    }
                } else {
                    //修改采样批次时，去除修改之前选择但现在去掉的全程空白样
                    if (!empty($post['cyd_id']) && !empty($cy_rec_qckb[$cy_rec_info['sid']]['id'])) {
                        $DB->query("DELETE FROM `cy_rec` where id='{$cy_rec_qckb[$cy_rec_info['sid']]['id']}'");
                        //$DB->query("DELETE FROM `assay_pay` where id='{$cy_rec_qckb[$cy_rec_info['sid']]['id']}'");
                        $DB->query("DELETE FROM `assay_order` where cid='{$cy_rec_qckb[$cy_rec_info['sid']]['id']}'"); //原样的质控标识在后面回进行覆盖
                    }
                }
                ##########现场加标站点的处理
                $xcjb_zk = '';
                if (in_array($cy_rec_info['sid'], $xcjb_sites)) {
                    $xcjb_cy_rec_info = [];
                    // $yuan_cid = $cid; //原样的cid
                    $site_xcjb_values = [];
                    $site_xcjb_values = array_filter(explode(",", $xcjb_values));
                    if (!empty($site_xcjb_values)) {
                        $xcjb_cy_rec_info = $cy_rec_info; //避免现场加标修改了原样的order表信息
                        $xcjb_bar_code = $xcjb_cy_rec_info['bar_code']; //记录现场平行原样的样品编号，后面现场项目插入order表用
                        $xcjb_cy_rec_info['bar_code'] = ''; //现场加标样的新样品编号
                        $xcjb_cy_rec_info['zk_flag'] = '11'; //现场平行质控标识
                        $xcjb_cy_rec_info['site_name'] .= '（现场加标）'; //现场加标站点名称
                        // $xcjb_cy_rec_info['bar_code'] = new_bar_code($cy_info['site_type'], $fater_water, $cy_info['cy_date'], $fix_bar_code); //现场平行样的新样品编号
                        $xcjb_zk = 1;
                        $xcjb_zk = '';
                        $xcjb_cy_rec_info['assay_values'] = implode(',', $site_xcjb_values);
                        //将默认采样容器瓶数写入采样rec表的json字段
                        // $rq_sql = "SELECT * FROM `rq_value` WHERE vid!='' AND fzx_id='" . $fzx_id . "'  AND `water_type` IN(0,{$xcjb_cy_rec_info['water_type']})  ORDER BY id";
                        $rq_sql = "SELECT * FROM `rq_value` WHERE vid!='' AND fzx_id='" . $fzx_id . "'  AND (find_in_set('0', water_type) or find_in_set('{$xcjb_cy_rec_info['water_type']}', water_type))  ORDER BY id";
                        $rq_query = $DB->query($rq_sql);
                        $tmp_rec_json = array();
                        if (!empty($cy_rec_old_xcjb[$xcjb_cy_rec_info['sid']]['json'])) {
                            $tmp_rec_json = json_decode($cy_rec_old_xcjb[$xcjb_cy_rec_info['sid']]['json'], true);
                            if ($tmp_rec_json['rq']) {
                                unset($tmp_rec_json['rq']); //清除历史容器信息
                            }
                        }
                        $avarr = $site_xcjb_values;
                        $no_xmmb_rq = true;
                        if (!empty($global['rq_value_relate'])) {
                            sort($assay_values_arr);
                            $cy_rec_info_sort_assay_values_str = implode(',', $assay_values_arr);
                            // 查询站点项目是否属于项目模板，属于则获取固定的采样容器及数量
                            if (array_search($cy_rec_info_sort_assay_values_str, $xmmb) !== false) {
                                $xmmb_id = array_search($cy_rec_info_sort_assay_values_str, $xmmb);
                                $rq_id_arr = [];
                                $rq_id_arr = array_keys($global['rq_value_relate'][$xmmb_id]);
                                foreach ($rq_id_arr as $_rq_id) {
                                    $tmp_rec_json['rq'][$_rq_id] = $global['rq_value_relate'][$xmmb_id][$_rq_id];
                                }
                                $no_xmmb_rq = false;
                            }
                        }
                        if ($no_xmmb_rq) {
                            while ($rq_rs = $DB->fetch_assoc($rq_query)) {
                                $rq_value = explode(',', $rq_rs['vid']);
                                $rq_conditions = json_decode($rq_rs['conditions'], true);
                                if ($global['rq_site_type']) {
                                    if (((!$post["kh_id"] && $rq_conditions['task_type']['operate'] == '3') || (!in_array($post['site_type'], $rq_conditions['site_type']) && !empty($rq_conditions['site_type']))) || ($post["kh_id"] && $rq_conditions['task_type']['operate'] == '2')) {
                                        continue;
                                    }
                                }
                                if (array_intersect($avarr, $rq_value)) {
                                    $mr_shu = empty($rq_conditions) ? $rq_rs['mr_shu'] : rq_conditions_result($rq_conditions, $avarr, $rq_rs);
                                    if ($mr_shu !== false) {
                                        $tmp_rec_json['rq'][$rq_rs['id']] = $mr_shu;
                                    }
                                }
                            }
                        }
                        $xcjb_cy_rec_info['json'] = JSON($tmp_rec_json);
                        //采样容器存储结束
                        if (empty($post['cyd_id']) || empty($cy_rec_old_xcjb[$xcjb_cy_rec_info['sid']]['id'])) {
                            $xcjb_cid = new_record('cy_rec', $xcjb_cy_rec_info);
                        } else {
                            $xcjb_cid = $cy_rec_old_xcjb[$xcjb_cy_rec_info['sid']]['id'];
                            $xcjb_cy_rec_info['bar_code'] = $cy_rec_old_xcjb[$xcjb_cy_rec_info['sid']]['bar_code'];
                            $xcjb_cy_rec_info['jcbz_id'] = $cy_rec_old_xcjb[$xcjb_cy_rec_info['sid']]['jcbz_id'];
                            $update_xcjb_cy_rec_info = $xcjb_cy_rec_info;
                            unset($update_xcjb_cy_rec_info['create_date']);
                            unset($update_xcjb_cy_rec_info['create_man']);
                            update_rec('cy_rec', $update_xcjb_cy_rec_info, $xcjb_cid);
                        }
                    }
                } else {
                    //修改采样批次时，去除修改之前选择但现在去掉的现场加标样
                    if (!empty($post['cyd_id']) && !in_array($cy_rec_info['sid'], $xcjb_sites) && !empty($cy_rec_old_xcjb[$cy_rec_info['sid']]['id'])) {
                        $DB->query("DELETE FROM `cy_rec` where id='{$cy_rec_old_xcjb[$cy_rec_info['sid']]['id']}'");
                        //$DB->query("DELETE FROM `assay_pay` where id='{$cy_rec_old_zk[$cy_rec_info['sid']]['id']}'");
                        $DB->query("DELETE FROM `assay_order` where cid='{$cy_rec_old_xcjb[$cy_rec_info['sid']]['id']}'"); //原样的质控标识在后面回进行覆盖
                    }
                }
                ##########现场平行站点的处理
                if ($cy_rec_info['zk_flag'] == 5) {
                    $yuan_cid = $cid; //原样的cid
                    $xcpx_bar_code = $cy_rec_info['bar_code']; //记录现场平行原样的样品编号，后面现场项目插入order表用
                    if ($global['xdcw_xcpx_last']) {
                        // 现场平行样品编号放最后
                        $all_px = count($value['sites']) + count($value['xcjb']); // 除现场平行外其它样品数量
                        // 全程空白是否需排在现场平行之后
                        if (!$global['xdcw_qckb_after_xcpx']) {
                            $all_px += count($value['qckb']);
                        }
                        $cy_rec_info['px'] = $all_px + $xcpx_px;
                        $xcpx_px++;
                    } else {
                        $cy_rec_info['px'] = ++$px; //rec排序
                    }
                    $add_xcpx_before_qxkb_flag && $px++;
                    $cy_rec_info['zk_flag'] = '-6'; //现场平行质控标识
                    $cy_rec_info['site_name'] .= '（现场平行）'; //现场平站点名称
                    //				$cy_rec_info['bar_code']= new_bar_code($cy_info['site_type'],$fater_water,$cy_info['cy_date'],$fix_bar_code);//现场平行样的新样品编号
                    $cy_rec_info['bar_code'] = ''; //现场平行样的新样品编号
                    $rs_siteArr['assay_values'] = explode(",", $rs_siteArr['assay_values']);
                    if (empty($xcpx_values)) {
                        $cy_rec_info['assay_values'] = implode(",", array_diff($rs_siteArr['assay_values'], $xcpx_value_arr)); //该现场平行样检测的项目（取差集的形式）
                    } else {
                        $xcpx_values_arr = explode(",", $xcpx_values);
                        $cy_rec_info['assay_values'] = implode(",", array_intersect($xcpx_values_arr, $rs_siteArr['assay_values'])); //该现场平行样检测的项目(批次表里存储的)
                    }
                    if ($global['huanjing_show']) {
                        if (empty($xcpx_milieu_values)) {
                            $cy_rec_info['milieu_values'] = $rs_siteArr['milieu_values'];
                        } else {
                            $xcpx_milieu_values_arr = explode(',', $xcpx_milieu_values);
                            $cy_rec_info['milieu_values'] = implode(",", array_intersect($xcpx_milieu_values_arr, explode(',', $rs_siteArr['milieu_values'])));//该现场平行样检测的项目(批次表里存储的)
                        }
                    }
                    //将默认采样容器瓶数写入采样rec表的json字段
                    //				$rq_sql		= "SELECT * FROM `rq_value` WHERE vid!='' AND fzx_id='".$fzx_id."'   AND `water_type` IN(0,{$cy_rec_info['water_type']})   ORDER BY id";
                    $rq_sql = "SELECT * FROM `rq_value` WHERE vid!='' AND fzx_id='" . $fzx_id . "'  AND (find_in_set('0', water_type) or find_in_set('{$cy_rec_info['water_type']}', water_type))  ORDER BY id";
                    $rq_query = $DB->query($rq_sql);
                    $tmp_rec_json = array();
                    if (!empty($cy_rec_old_zk[$cy_rec_info['sid']]['json'])) {
                        $tmp_rec_json = json_decode($cy_rec_old_zk[$cy_rec_info['sid']]['json'], true);
                        if ($tmp_rec_json['rq']) {
                            unset($tmp_rec_json['rq']); //清除历史容器信息
                        }
                    }
                    if ($global['cyrw']['xc_yq']) {
                        $avarr = explode(',', $cy_rec_info['assay_values']);
                    } else {
                        $avarr = array_diff(explode(',', $cy_rec_info['assay_values']), $xc_exam_arr);
                    }
                    $no_xmmb_rq = true;
                    if (!empty($global['rq_value_relate'])) {
                        sort($assay_values_arr);
                        $cy_rec_info_sort_assay_values_str = implode(',', $assay_values_arr);
                        // 查询站点项目是否属于项目模板，属于则获取固定的采样容器及数量
                        if (array_search($cy_rec_info_sort_assay_values_str, $xmmb) !== false) {
                            $xmmb_id = array_search($cy_rec_info_sort_assay_values_str, $xmmb);
                            $rq_id_arr = [];
                            $rq_id_arr = array_keys($global['rq_value_relate'][$xmmb_id]);
                            foreach ($rq_id_arr as $_rq_id) {
                                $tmp_rec_json['rq'][$_rq_id] = $global['rq_value_relate'][$xmmb_id][$_rq_id];
                            }
                            $no_xmmb_rq = false;
                        }
                    }
                    if ($no_xmmb_rq) {
                        while ($rq_rs = $DB->fetch_assoc($rq_query)) {
                            $rq_value = explode(',', $rq_rs['vid']);
                            $rq_conditions = json_decode($rq_rs['conditions'], true);
                            if ($global['rq_site_type']) {
                                if (((!$post["kh_id"] && $rq_conditions['task_type']['operate'] == '3') || (!in_array($post['site_type'], $rq_conditions['site_type']) && !empty($rq_conditions['site_type']))) || ($post["kh_id"] && $rq_conditions['task_type']['operate'] == '2')) {
                                    continue;
                                }
                            }
                            if (array_intersect($avarr, $rq_value)) {
                                $mr_shu = empty($rq_conditions) ? $rq_rs['mr_shu'] : rq_conditions_result($rq_conditions, $avarr, $rq_rs);
                                if ($mr_shu !== false) {
                                    $tmp_rec_json['rq'][$rq_rs['id']] = $mr_shu;
                                }
                            }
                        }
                    }
                    $cy_rec_info['json'] = JSON($tmp_rec_json);
                    //采样容器存储结束
                    if (empty($post['cyd_id']) || empty($cy_rec_old_zk[$cy_rec_info['sid']]['id'])) {
                        $cid = new_record('cy_rec', $cy_rec_info);
                    } else {
                        $cid = $cy_rec_old_zk[$cy_rec_info['sid']]['id'];
                        $cy_rec_info['bar_code'] = $cy_rec_old_zk[$cy_rec_info['sid']]['bar_code'];
                        $cy_rec_info['jcbz_id'] = $cy_rec_old_zk[$cy_rec_info['sid']]['jcbz_id'];
                        $update_cy_rec_info = $cy_rec_info;
                        unset($update_cy_rec_info['create_date']);
                        unset($update_cy_rec_info['create_man']);
                        update_rec('cy_rec', $update_cy_rec_info, $cid);
                    }
                }
                //修改采样批次时，去除修改之前选择但现在去掉的现场平行样
                if (!empty($post['cyd_id']) && $cy_rec_info['zk_flag'] == 0 && !empty($cy_rec_old_zk[$cy_rec_info['sid']]['id'])) {
                    $DB->query("DELETE FROM `cy_rec` where id='{$cy_rec_old_zk[$cy_rec_info['sid']]['id']}'");
                    //$DB->query("DELETE FROM `assay_pay` where id='{$cy_rec_old_zk[$cy_rec_info['sid']]['id']}'");
                    $DB->query("DELETE FROM `assay_order` where cid='{$cy_rec_old_zk[$cy_rec_info['sid']]['id']}'"); //原样的质控标识在后面回进行覆盖
                }
                #########现场检测项目的处理:往assay_order表里插入数据
                //采样批次修改时先去掉无关的order表记录
                if (!empty($post['cyd_id'])) {
                    //去掉被取消选择的现场检测项目
                    $old_xc_value = explode(",", $cy_rs['xc_exam_value']);
                    $new_xc_value = explode(",", $cy_info['xc_exam_value']);
                    $del_xc_value = implode(",", array_diff($old_xc_value, $new_xc_value));
                    if ($del_xc_value != '') {
                        $DB->query("DELETE FROM `assay_order` WHERE cyd_id='{$post['cyd_id']}' AND vid in ({$del_xc_value})");
                    }
                    //再去掉站点里取消选择的现场检测项目
                    if ($cy_rec_info['zk_flag'] == '-6') {
                        $old_cid = $cy_rec_old_zk[$cy_rec_info['sid']]['id'];
                        $old_vid = explode(",", $cy_rec_old_zk[$cy_rec_info['sid']]['assay_values']);
                        $old_sites_values_str = implode(",", array_diff($old_vid, $assay_values_arr));
                        if ($old_sites_values_str != '') {
                            //现场平行的原样处理
                            $DB->query("DELETE FROM `assay_order` WHERE cid='{$old_cid}' and vid in ({$old_sites_values_str})");
                        }
                    }
                    if (!empty($xcjb_cy_rec_info) && $xcjb_cy_rec_info['zk_flag'] == '10') {
                        $old_cid = $cy_rec_old_xcjb[$cy_rec_info['sid']]['id'];
                        $old_vid = explode(",", $cy_rec_old_xcjb[$cy_rec_info['sid']]['assay_values']);
                        $$old_sites_values_str = implode(",", array_diff($old_vid, $site_xcjb_values));
                        if ($old_sites_values_str != '') {
                            //现场加标的处理
                            $DB->query("DELETE FROM `assay_order` WHERE cid='{$old_cid}' and vid in ({$old_sites_values_str})");
                        }
                    }
                    $old_cid = $cy_rec_old[$cy_rec_info['sid']]['id'];
                    $old_vid = explode(",", $cy_rec_old[$cy_rec_info['sid']]['assay_values']);
                    $old_sites_values_str = implode(",", array_diff($old_vid, $assay_values_arr));
                    if ($old_sites_values_str != '') {
                        //现场平行的平行样处理
                        $DB->query("DELETE FROM `assay_order` WHERE cid='{$old_cid}' and vid in ({$old_sites_values_str})");
                    }
                }
                if (!empty($cy_info['xc_exam_value'])) {
                    $insert_order = array();
                    $insert_order['cyd_id'] = $cy_rec_info['cyd_id']; //采样单id
                    $insert_order['cid'] = $cid; //cy_rec表id
                    $insert_order['sid'] = $cy_rec_info['sid']; //站点表id
                    $insert_order['water_type'] = $cy_rec_info['water_type']; //水样类型
                    $insert_order['site_name'] = $cy_rec_info['site_name']; //站点名称
                    $insert_order['river_name'] = $cy_rec_info['river_name']; //河流名称
                    $insert_order['bar_code'] = $cy_rec_info['bar_code']; //样品编号
                    $insert_order['assay_over'] = '0'; //化验单某样品完成状态
                    $insert_order['create_date'] = $cy_rec_info['create_date']; //化验单创建时间
                    //将所有的现场检测项目插入到assay_order表
                    $assay_values = array_intersect($assay_values_arr, $xc_exam_arr); //取出这个站点所测的现场检测项目（取交集）
                    if (empty($xc_water_type[$insert_order['water_type']])) {
                        $xc_water_type[$insert_order['water_type']] = array();
                    }
                    $xc_water_type[$insert_order['water_type']] = array_unique(array_merge($assay_values, $xc_water_type[$insert_order['water_type']]));
                    $xcpx_value_arr_rec = explode(",", $cy_rec_info['assay_values']); //站点所测的项目
                    $qckbvalues = explode(',', $cy_rec_qckb_info['assay_values']); //站点所测的全程空白项目
                    $xcjbvalues = explode(',', $xcjb_cy_rec_info['assay_values']); //站点所测的现场加标项目
                    foreach ($assay_values as $vid) {
                        $insert_order['vid'] = $vid; //化验项目id
                        if ($cy_rec_info['zk_flag'] == '-6' && !in_array($vid, $xcpx_value_arr_rec)) {
                            $insert_order['cid'] = $yuan_cid;
                            $insert_order['hy_flag'] = '0'; //质控标识
                            $insert_order['bar_code'] = $xcpx_bar_code; //现场平行原样的样品编号
                        } else if ($cy_rec_info['zk_flag'] == '-6') {
                            $insert_order['hy_flag'] = '-6'; //现场平行样的hy_flag
                            $insert_order['bar_code'] = $cy_rec_info['bar_code']; //样品编号
                            $insert_order['cid'] = $cid; //cy_rec表id
                            //修改采样任务时，现场平行样的修改
                            if (empty($post['cyd_id']) || empty($order_old[$insert_order['cid']][$vid])) {
                                new_record('assay_order', $insert_order); //将现场平行样信息插入到assay_order表
                            } else {
                                $order_id = $order_old[$insert_order['cid']][$vid]['id'];
                                $update_order = $insert_order;
                                unset($update_order['bar_code']);
                                unset($update_order['create_date']);
                                unset($update_order['cyd_id']);
                                unset($update_order['vid']);
                                unset($update_order['sid']);
                                update_rec('assay_order', $update_order, $order_id);
                            }
                            $insert_order['hy_flag'] = '5'; //现场平行原样的hy_flag
                            $insert_order['cid'] = $yuan_cid;
                            $insert_order['bar_code'] = $xcpx_bar_code; //现场平行原样的样品编号
                        } else if ($qckb_flag == '1' && in_array($vid, $qckbvalues)) {
                            $insert_order['hy_flag'] = '1'; //qckb样的hy_flag
                            $insert_order['bar_code'] = $cy_rec_qckb_info['bar_code']; //样品编号
                            $insert_order['cid'] = $qckb_cid; //cy_rec表id
                            $insert_order['site_name'] = $cy_rec_qckb_info['site_name'];
                            $insert_order['river_name'] = $cy_rec_qckb_info['river_name'];
                            $insert_order['sid'] = $cy_rec_qckb_info['sid'];
                            //修改采样任务时，qckb样的修改
                            if (empty($post['cyd_id']) || empty($order_old[$insert_order['cid']][$vid])) {
                                new_record('assay_order', $insert_order); //将现场平行样信息插入到assay_order表
                            } else {
                                $order_id = $order_old[$insert_order['cid']][$vid]['id'];
                                $update_order = $insert_order;
                                unset($update_order['bar_code']);
                                unset($update_order['create_date']);
                                unset($update_order['cyd_id']);
                                unset($update_order['vid']);
                                unset($update_order['sid']);
                                update_rec('assay_order', $update_order, $order_id);
                            }
                            $insert_order['site_name'] = $cy_rec_info['site_name'];
                            $insert_order['river_name'] = $cy_rec_info['river_name'];
                            $insert_order['sid'] = $cy_rec_info['sid'];
                            $insert_order['hy_flag'] = '0'; //qckb原样的hy_flag
                            $insert_order['cid'] = $yuan_cid;
                            $insert_order['bar_code'] = $qckb_bar_code; //qckb原样的样品编号
                        } else {
                            //正常的标识恢复
                            $insert_order['hy_flag'] = $cy_rec_info['zk_flag']; //质控标识
                        }
                        //这个站点做全程空白也做平行的情况
                        if ($qckb_flag == '1' && in_array($vid, $qckbvalues) && $cy_rec_info['zk_flag'] == '-6') {
                            $insert_order['hy_flag'] = '1'; //qckb样的hy_flag
                            $insert_order['bar_code'] = $cy_rec_qckb_info['bar_code']; //样品编号
                            $insert_order['cid'] = $qckb_cid; //cy_rec表id
                            $insert_order['site_name'] = $cy_rec_qckb_info['site_name'];
                            $insert_order['river_name'] = $cy_rec_qckb_info['river_name'];
                            $insert_order['sid'] = $cy_rec_qckb_info['sid'];
                            //修改采样任务时，qckb样的修改
                            if (empty($post['cyd_id']) || empty($order_old[$insert_order['cid']][$vid])) {
                                new_record('assay_order', $insert_order); //将现场平行样信息插入到assay_order表
                            } else {
                                $order_id = $order_old[$insert_order['cid']][$vid]['id'];
                                $update_order = $insert_order;
                                unset($update_order['bar_code']);
                                unset($update_order['create_date']);
                                unset($update_order['cyd_id']);
                                unset($update_order['vid']);
                                unset($update_order['sid']);
                                update_rec('assay_order', $update_order, $order_id);
                            }
                            $insert_order['site_name'] = $rs_site_name;
                            $insert_order['river_name'] = $cy_rec_info['river_name'];
                            $insert_order['sid'] = $cy_rec_info['sid'];
                            $insert_order['hy_flag'] = '5'; //qckb原样的hy_flag
                            $insert_order['cid'] = $yuan_cid;
                            $insert_order['bar_code'] = $qckb_bar_code; //qckb原样的样品编号
                        }
                        //这个站点做现场加标
                        if (in_array($vid, $xcjbvalues) && $xcjb_cy_rec_info['zk_flag'] == '11') {
                            $insert_order_xcjb = $insert_order;
                            $insert_order_xcjb['hy_flag'] = '11'; //xcjb样的hy_flag
                            $insert_order_xcjb['bar_code'] = $xcjb_cy_rec_info['bar_code']; //样品编号
                            $insert_order_xcjb['cid'] = $xcjb_cid; //cy_rec表id
                            $insert_order_xcjb['site_name'] = $xcjb_cy_rec_info['site_name'];
                            $insert_order_xcjb['river_name'] = $xcjb_cy_rec_info['river_name'];
                            $insert_order_xcjb['sid'] = $xcjb_cy_rec_info['sid'];
                            //修改采样任务时，qckb样的修改
                            if (empty($post['cyd_id']) || empty($order_old[$insert_order_xcjb['cid']][$vid])) {
                                new_record('assay_order', $insert_order_xcjb); //将现场平加标信息插入到assay_order表
                            } else {
                                $order_id_xcjb = $order_old[$insert_order_xcjb['cid']][$vid]['id'];
                                $update_order_xcjb = $insert_order_xcjb;
                                unset($update_order_xcjb['bar_code']);
                                unset($update_order_xcjb['create_date']);
                                unset($update_order_xcjb['cyd_id']);
                                unset($update_order_xcjb['vid']);
                                unset($update_order_xcjb['sid']);
                                update_rec('assay_order', $update_order_xcjb, $order_id_xcjb);
                            }
                        }
                        //正常样的修改
                        if (empty($post['cyd_id']) || empty($order_old[$insert_order['cid']][$vid])) {
                            new_record('assay_order', $insert_order); //将信息插入到assay_order表
                        } else {
                            $order_id = $order_old[$insert_order['cid']][$vid]['id'];
                            $update_order = $insert_order;
                            unset($update_order['bar_code']);
                            unset($update_order['create_date']);
                            unset($update_order['cyd_id']);
                            unset($update_order['vid']);
                            unset($update_order['sid']);
                            update_rec('assay_order', $update_order, $order_id);
                        }
                    }
                }
            }
            ###############查询出需要插入assay_pay表的现场检测项目的所有信息并插入到assay_pay表中
            $water_types = implode(',', $water_type_arr);
            $xc_exam_arr = array_intersect($all_assay_values, $xc_exam_arr); //所选现场检测项目与所有站点项目取交集，去掉站点不测却又被选中的现场检测项目
            $cy_info['xc_exam_value'] = implode(",", $xc_exam_arr);
            if (!empty($cy_info['xc_exam_value'])) {
                //取出水样类型的大类和小类
                $water_type_fenlei = array();
                $sql_leixing = $DB->query("SELECT * FROM `leixing` WHERE act='1' AND id in($water_types)");
                while ($rs_leixing = $DB->fetch_assoc($sql_leixing)) {
                    if ($rs_leixing['parent_id'] == '0') {
                        $water_type_fenlei[$rs_leixing['id']] = $rs_leixing['id'];
                    } else {
                        $water_type_fenlei[$rs_leixing['id']] = $rs_leixing['parent_id'];
                    }
                }
                $insert_pay = $values_name = array();
                $insert_pay['cyd_id'] = $cy_rec_info['cyd_id'];
                $insert_pay['fzx_id'] = $fzx_id;
                $insert_pay['fp_id'] = $fzx_id;
                $insert_pay['create_date'] = $cy_rec_info['create_date'];
                $insert_pay['is_xcjc'] = '1';
                //取出不同水样类型下的项目名称
                $where_water_type = implode(",", $water_type_fenlei);
                $sql_pay_value = $DB->query("SELECT bz.vid,bz.value_C,n_set.module_value2 FROM `n_set` INNER JOIN `assay_jcbz` AS bz ON n_set.id = bz.jcbz_bh_id
									  WHERE n_set.module_name='jcbz_bh' AND n_set.module_value2 in ($where_water_type) AND n_set.module_value3 = '1' AND n_set.act = '1' AND bz.vid IN ({$cy_info['xc_exam_value']})");
                while ($rs_pay_value = $DB->fetch_assoc($sql_pay_value)) {
                    //格式：arr[vid][water_type]=>项目名
                    if (empty($rs_pay_value['value_C'])) {
                        //如果标准里没有此项目名就到session中去找
                        $rs_pay_value['value_C'] = $_SESSION['assayvalueC'][$rs_pay_value['vid']];
                    }
                    $values_name[$rs_pay_value['vid']][$rs_pay_value['module_value2']] = $rs_pay_value['value_C'];
                }
                $values_fangfa = array();
                if ($global['xd_cyrw']['group_bind_yiqi']) {
                    $gr_info = $DB->fetch_one_assoc("select `json` from site_group where `id` = '{$gr_id}' ");
                    $gr_json_arr = json_decode($gr_info['json'], true);
                }
                foreach ($xc_water_type as $key_water_type => $value_vids) {
                    foreach ($value_vids as $value_vid) {
                        //取出方法表配置的一些信息
                        //$values_fangfa	= array();
                        $num_pay_xmfa = 0;
                        if ($global['hyd']['new_jcxm_set']) {
                            $sql_pay_xmfa = $DB->query("SELECT xmfa . * , yiqi.yq_mingcheng,yiqi.yq_sbbianhao,me.method_number,me.method_name FROM `xmfa` LEFT JOIN `yiqi` AS yiqi ON xmfa.yiqi = yiqi.id LEFT JOIN `assay_method` AS me ON xmfa.fangfa=me.id
													WHERE  xmfa.fzx_id='$fzx_id' AND FIND_IN_SET('{$key_water_type}', `lx_ids`) AND FIND_IN_SET('{$key_water_type}', `mrlx_ids`) AND xmfa.xmid='$value_vid' AND xmfa.act='1' GROUP BY xmfa.xmid order by xmfa.xmid");
                            $num_pay_xmfa = $DB->num_rows($sql_pay_xmfa);
                            //如果小类中没有方法，就取大类中的方法
                            if ($num_pay_xmfa < 1) {
                                $sql_pay_xmfa = $DB->query("SELECT xmfa . * , yiqi.yq_mingcheng,yiqi.yq_sbbianhao,me.method_number,me.method_name FROM `xmfa` LEFT JOIN `yiqi` AS yiqi ON xmfa.yiqi = yiqi.id LEFT JOIN `assay_method` AS me ON xmfa.fangfa=me.id WHERE  xmfa.fzx_id='$fzx_id' AND FIND_IN_SET('{$water_type_fenlei[$key_water_type]}', `lx_ids`) AND FIND_IN_SET('{$water_type_fenlei[$key_water_type]}', `mrlx_ids`) AND xmfa.xmid='$value_vid' AND xmfa.act='1' GROUP BY xmfa.xmid order by xmfa.xmid");
                                $num_pay_xmfa = $DB->num_rows($sql_pay_xmfa);
                            }
                        }
                        if ($num_pay_xmfa < 1) {
                            $sql_pay_xmfa = $DB->query("SELECT xmfa . * , yiqi.yq_mingcheng,yiqi.yq_sbbianhao,me.method_number,me.method_name FROM `xmfa` LEFT JOIN `yiqi` AS yiqi ON xmfa.yiqi = yiqi.id LEFT JOIN `assay_method` AS me ON xmfa.fangfa=me.id
													WHERE  xmfa.fzx_id='$fzx_id' AND xmfa.lxid='$key_water_type' AND xmfa.xmid='$value_vid' AND xmfa.act='1' AND xmfa.mr='1' order by xmfa.xmid");
                            $num_pay_xmfa = $DB->num_rows($sql_pay_xmfa);
                            //如果小类中没有方法，就取大类中的方法
                            if ($num_pay_xmfa < 1) {
                                $sql_pay_xmfa = $DB->query("SELECT xmfa . * , yiqi.yq_mingcheng,yiqi.yq_sbbianhao,me.method_number,me.method_name FROM `xmfa` LEFT JOIN `yiqi` AS yiqi ON xmfa.yiqi = yiqi.id LEFT JOIN `assay_method` AS me ON xmfa.fangfa=me.id WHERE  xmfa.fzx_id='$fzx_id' AND xmfa.lxid='{$water_type_fenlei[$key_water_type]}' AND xmfa.xmid='$value_vid' AND xmfa.act='1' AND xmfa.mr='1' order by xmfa.xmid");
                            }
                        }
                        while ($rs_pay_xmfa = $DB->fetch_assoc($sql_pay_xmfa)) {
                            // xmfa表内数据转存
                            $rs_pay_xmfa_arr = $rs_pay_xmfa;
                        }
                        $insert_pay['vid'] = $rs_pay_xmfa_arr['xmid'] ? $rs_pay_xmfa_arr['xmid'] : $value_vid;    // 检测项目id
                        // 检测项目名称
                        if (!empty($rs_pay_xmfa_arr['xmName'])) {
                            // 优先使用【检验方法设置】中的项目别名
                            $insert_pay['assay_element'] = $rs_pay_xmfa_arr['xmName'];
                        } elseif (!empty($values_name[$insert_pay['vid']][$water_type_fenlei[$key_water_type]])) {
                            // 使用【评价标准】中的项目名称
                            $insert_pay['assay_element'] = $values_name[$insert_pay['vid']][$water_type_fenlei[$key_water_type]];
                        } elseif (!empty($_SESSION['assayvalueC'][$insert_pay['vid']])) {
                            //如果标准中没有此项目的名称，就到session中去找
                            $insert_pay['assay_element'] = $_SESSION['assayvalueC'][$insert_pay['vid']];
                        } else {
                            // 都没有找到使用assay_value表中的检测项目名称
                            $insert_pay['assay_element'] = $all_xm_list[$insert_pay['vid']];
                        }
                        $insert_pay['userid'] = $cy_info['cy_user'];
                        $insert_pay['userid2'] = $cy_info['cy_user2'];
                        $insert_pay['userids'] = $cy_info['cy_users'];
                        $insert_pay['uid'] = $renarr[$cy_info['cy_user']];
                        $insert_pay['uid2'] = $renarr[$cy_info['cy_user2']];
                        $cy_users_arr = explode(',', $cy_info['cy_users']);
                        $pay_uid = [];
                        foreach ($cy_users_arr as $k => $v) {
                            $pay_uid[] = $renarr[$v];
                        }
                        $uid_str = implode(',', $pay_uid);
                        $insert_pay['uids'] = $uid_str;
                        $insert_pay['unit'] = $rs_pay_xmfa_arr['unit'] ? $rs_pay_xmfa_arr['unit'] : "";    // 项目检测单位
                        // td1:检测方法名称,td2:方法号 判断td1,td2是否合并
                        if ($global['cy_record']['merge_td1_td2']) {
                            // td1-td2数据合并到td1内，td2-td1数据合并到td2内
                            if (in_array('td1-td2', $global['xc_xinxi_list'])) {
                                if (empty($rs_pay_xmfa_arr['method_name']) && empty($rs_pay_xmfa_arr['method_number'])) {
                                    $insert_pay['td1'] = "";
                                } else {
                                    $insert_pay['td1'] = $rs_pay_xmfa_arr['method_name'] . $rs_pay_xmfa_arr['method_number'];
                                }
                                $insert_pay['td2'] = "";
                            } elseif (in_array('td2-td1', $global['xc_xinxi_list'])) {
                                $insert_pay['td1'] = "";
                                if (empty($rs_pay_xmfa_arr['method_name']) && empty($rs_pay_xmfa_arr['method_number'])) {
                                    $insert_pay['td2'] = "";
                                } else {
                                    $insert_pay['td2'] = $rs_pay_xmfa_arr['method_name'] . $rs_pay_xmfa_arr['method_number'];
                                }
                            }
                        } else {
                            $insert_pay['td1'] = $rs_pay_xmfa_arr['method_name'] ? $rs_pay_xmfa_arr['method_name'] : ""; //$rs_pay_xmfa['fangfa'];
                            $insert_pay['td2'] = $rs_pay_xmfa_arr['method_number'] ? $rs_pay_xmfa_arr['method_number'] : ""; //$rs_pay_xmfa['fangfa'];
                        }
                        //  保存时 优先获取批次绑定的仪器信息
                        if ($global['xd_cyrw']['group_bind_yiqi'] && !empty($gr_json_arr['yiqi']) && array_key_exists($value_vid, $gr_json_arr['yiqi'])) {
                            $yiqi_id = $gr_json_arr['yiqi'][$value_vid];
                            $yiqi_info = $DB->fetch_one_assoc("select id,yq_mingcheng,yq_sbbianhao,yq_neibubh,yq_xinghao,yq_jiandingriqi,yq_jdriqi,yq_jdzhouqi,yq_jzrq,yq_jzzhouqi,is_jianding,is_jiaozhun from yiqi where `id` = '{$yiqi_id}' ");
                            $rs_pay_xmfa_arr['yiqi'] = $yiqi_info['id'];
                            $rs_pay_xmfa_arr['yq_mingcheng'] = $yiqi_info['yq_mingcheng'];
                            $rs_pay_xmfa_arr['yq_xinghao'] = $yiqi_info['yq_xinghao'];
                            $rs_pay_xmfa_arr['yq_sbbianhao'] = $yiqi_info['yq_neibubh'];
                            $yiqi_youxiao_date = '';
                            if (!empty($yiqi_info['yq_jiandingriqi']) && $yiqi_info['is_jianding'] == 1) { //有些仪器是校准的，不用检定，如果检定没有填写数据的，就用校准日期+校准周期  并判断是否检定
                                $yiqi_youxiao_date = empty($yiqi_info['yq_jdriqi']) ? date('Y-m-d', strtotime("+{$yiqi_info['yq_jdzhouqi']} month -1 day", strtotime($yiqi_info['yq_jiandingriqi']))) : date('Y-m-d', strtotime("+{$yiqi_info['yq_jdriqi']} month -1 day", strtotime($yiqi_info['yq_jiandingriqi'])));
                            } else if (!empty($yiqi_info['yq_jzrq']) && $yiqi_info['is_jiaozhun'] == 1) {  // 并判断是否校准
                                $yiqi_youxiao_date = date('Y-m-d', strtotime("+{$yiqi_info['yq_jzzhouqi']} month -1 day", strtotime($yiqi_info['yq_jzrq'])));
                            }
                            $insert_pay['yiqi_youxiao_date'] = $yiqi_youxiao_date;  //仪器有效日期
                        }
                        $insert_pay['td3'] = $rs_pay_xmfa_arr['jcx'] ? $rs_pay_xmfa_arr['jcx'] : "";    //检出限
                        $insert_pay['yiqi_id'] = $rs_pay_xmfa_arr['yiqi'] ? $rs_pay_xmfa_arr['yiqi'] : "";    //仪器id
                        $insert_pay['td4'] = $rs_pay_xmfa_arr['yq_mingcheng'] ? $rs_pay_xmfa_arr['yq_mingcheng'] : "";    //仪器名称
                        $insert_pay['td5'] = $rs_pay_xmfa_arr['yq_xinghao'] ? $rs_pay_xmfa_arr['yq_xinghao'] : "";    //仪器型号
                        $insert_pay['yq_bh'] = $rs_pay_xmfa_arr['yq_sbbianhao'] ? $rs_pay_xmfa_arr['yq_sbbianhao'] : "";    //仪器设备编号
                        $insert_pay['table_id'] = $rs_pay_xmfa_arr['hyd_bg_id'] ? $rs_pay_xmfa_arr['hyd_bg_id'] : "";    //化验单表格id
                        $insert_pay['fangfa_id'] = $rs_pay_xmfa_arr['fangfa'] ? $rs_pay_xmfa_arr['fangfa'] : "";    //方法id
                        $insert_pay['fid'] = $rs_pay_xmfa_arr['id'] ? $rs_pay_xmfa_arr['id'] : "";    //项目法表的id
                        if (!@array_key_exists($rs_pay_xmfa_arr['fangfa'], $values_fangfa[$insert_pay['vid']])) {
                            $tid = new_record('assay_pay', $insert_pay); //将信息插入到assay_pay表
                            $values_fangfa[$insert_pay['vid']][$rs_pay_xmfa_arr['fangfa']] = $tid;
                            if (!empty($tid)) {
                                $pc_xcjc_xm_arr[] = $insert_pay['vid'];    //生成pay表的现场检测项目
                            }
                        }
                        $tid = $values_fangfa[$insert_pay['vid']][$rs_pay_xmfa_arr['fangfa']];
                        //全程序空白没有水样类型，默认都更新它
                        $DB->query("UPDATE `assay_order` SET tid='$tid' WHERE cyd_id='{$insert_pay['cyd_id']}' AND vid='{$insert_pay['vid']}' AND (water_type='$key_water_type' OR hy_flag='1')");
                        unset($rs_pay_xmfa_arr);
                    }
                }
            }
            $pc_xcjc_xm_str = implode(",", array_unique($pc_xcjc_xm_arr));
            //将统计的 水样类型 插入到cy表里
            $water_types = trim($water_types, ',');
            $DB->query("UPDATE `cy` SET water_type='$water_types',`xc_exam_value`='{$pc_xcjc_xm_str}' WHERE id='$cyd_id'");
            $cyd_id_list[] = $cyd_id; //记录cyd_id，插入监测计划表用
            $xy_i++;
        }
    }
// 开始生成样品编号
    $bar_code_place = get_bar_code_create_place();
    $bar_code_order = get_bar_code_create_order();
    $bar_code_auto = get_bar_code_create_auto();
// 生成采样编号
    if ($global['cy_bh']) {
        $cybh_is_update = $post['cyd_id'] ? true : false;
        $new_cy_bh_query = $DB->query("SELECT `id`,`cy_date` FROM `cy` WHERE `id` IN(" . implode(',', $cyd_arr) . ") order by `id`");
        $i = 0;
        while ($new_cy_bh_row = $DB->fetch_assoc($new_cy_bh_query)) {
            $i++;
            $num = count($cyd_arr) - $i;
            // 判断当前系统的生成采样编号的方法是否存在
            $func_name = "{$dw_biaozhi}_cy_bh";
            if (function_exists($func_name)) {
                $func_name($fzx_id, $new_cy_bh_row['id'], $new_cy_bh_row['cy_date'], $num, $cybh_is_update);
            } else {
                default_cy_bh($fzx_id, $new_cy_bh_row['id'], $new_cy_bh_row['cy_date'], $num, $cybh_is_update);
            }
        }
    }
    if ($bar_code_auto == 'auto' && $bar_code_place == 'xdrw') {
        $cyd_ids = implode(",", $cyd_arr);
        $new_cr_info = [];
        $rec_px = 'cr.id';
        if ($global['xdcw_xcpx_last'] || $global['xdcw_qckb_after_xcpx']) {
            //排序规则
            $rec_px = 'cr.px,cr.id';
        }
        $new_cy_query = $DB->query("SELECT cy.site_type,cy.cy_date as cy_cy_date,cr.* FROM cy_rec as cr left join cy on cy.id=cr.cyd_id WHERE cy.id IN($cyd_ids) order by {$rec_px}");
        while ($row = $DB->fetch_assoc($new_cy_query)) {
            $new_cr_info[$row['cyd_id']][$row['id']] = $row;
        }
        foreach ($new_cr_info as $_cyd_id => $cr) {
            $new_cids = array_keys($cr);
            if ($bar_code_order == 'no_order') {
                shuffle($new_cids);
            }
            foreach ($new_cids as $key => $_cid) {
                $_cr_info = $cr[$_cid];
                if ($_cr_info['bar_code'] != '') {
                    continue;
                }
                $_sid = $_cr_info['sid'] != 0 ? $_cr_info['sid'] : $_cr_info['kb_sid'];
                $_site_info = $DB->fetch_one_assoc("select * from sites where id='{$_sid}'");
                if (!empty($_cr_info['water_type'])) {
                    $fater_water = $_cr_info['water_type']; //没有水样类型的样品，自动按照上一个样品的水样类型生成编号
                }
                if ($global['cyrw']['site_bar_code'] && in_array($post['site_type'], $global['cyrw']['type_bar_code'])) {
                    if (!empty($dw_biaozhi)) {
                        $func_name_bar = $dw_biaozhi . '_new_bar_code';
                    }
                    if (function_exists($func_name_bar)) {
                        $new_code = $func_name_bar($_cr_info['site_type'], $fater_water, $_cr_info['cy_cy_date'], $_site_info); //个性生成采样单编号的函数
                    }
                } else {
                    $new_code = new_bar_code($_cr_info['site_type'], $fater_water, $_cr_info['cy_cy_date'], $_site_info['fix_bar_code']);
                }
                $DB->query("update cy_rec set bar_code='{$new_code}' where id='{$_cid}'");
                $DB->query("update assay_order set bar_code='{$new_code}' where cid='{$_cid}'");
            }
        }
        // #25903 生成报告编号后，自动生成报告编号
        if ($global['get_bgbh_after_create_bar_code']) {
            $global['get_bgbh_after_create_bar_code_flag'] = true;
            include_once '../report/bg_func.php';
            include_once '../report/get_bgbh_func.php';
            foreach ($cyd_arr as $cyd_id) {
                $already_get_bgbh_flag = false;
                // 生成report数据
                $select_rec_sql = insert_report_if_need($cyd_id);
                $select_rec_query = $DB->query($select_rec_sql);
                while ($c = $DB->fetch_assoc($select_rec_query)) {
                    // 生成报告编号
                    $_REQUEST['cids'] = $c['id'];
                    $_REQUEST['cyd_id'] = $cyd_id;
                    $_REQUEST['sid'] = $c['sid'];
                    $_REQUEST['not_disp_report'] = 1;
                    if (!$already_get_bgbh_flag) {
                        include '../report/bg_chakan.php';
                        $already_get_bgbh_flag = true;
                    }
                }
            }
            $global['get_bgbh_after_create_bar_code_flag'] = false;
        }
    }
// 任务生成完成后，获取所有的容器信息保存到cy表
    $rq_query = $DB->query("select * from rq_value");
    $rq_value_all = [];
    while ($row = $DB->fetch_assoc($rq_query)) {
        $rq_value_all[$row['id']] = $row;
    }
    foreach ($cyd_arr as $cyd_id) {
        $rec_query = $DB->query("select * from cy_rec where cyd_id='{$cyd_id}'");
        $cy_rq_info = [];
        while ($row = $DB->fetch_assoc($rec_query)) {
            $rq_json = json_decode($row['json'], true)['rq'];
            foreach ($rq_json as $_rqid => $_rqv) {
                $cy_rq_info[$_rqid] = $rq_value_all[$_rqid];
            }
        }
        ksort($cy_rq_info);
        $DB->query("update cy set rq_info='" . JSON($cy_rq_info) . "' where id='{$cyd_id}'");
    }

//任务生成完成后，获取科室设置信息保存到cy表

    $column_name = $DB->fetch_one_assoc("SELECT `COLUMN_NAME` FROM `information_schema`.`COLUMNS` WHERE `TABLE_SCHEMA`='{$DB->dbname}' AND `TABLE_NAME`='cy' AND `COLUMN_NAME` ='ks_info'");
    if ('ks_info' == $column_name['COLUMN_NAME']) {
        $ks_set = $DB->query("select * from n_set WHERE  fzx_id='" . $fzx_id . "' AND module_name='keshi_xm_set'");
        $ks_set_data = [];
        while ($row = $DB->fetch_assoc($ks_set)) {
            $ks_set_data[] = $row;
        }

        $DB->query("update cy set ks_info='" . JSON($ks_set_data) . "' where id='{$cyd_id}'");
    }

    if ($xy_i > 0) {
        if ($post['ajax_return'] == '1') {
            if ($global["customer"]['new_customer']) {
                $DB->query("update `customer` set `cyd_id`='{$cyd_id}' where `id` = '{$post['kh_id']}'");
                $query = $DB->query("select * from `customer_rec` where `customer_id`='{$post['kh_id']}' and `act`='1'");
                while ($row = $DB->fetch_assoc($query)) {
                    $info = $DB->fetch_one_assoc("select * from `cy_rec` where `cyd_id`='$cyd_id' and `sid`='{$row['sid']}'");
                    if (!empty($info['id'])) {
                        // 对采样时间进行判断
                        if ($row['cy_time'] && strtotime($row['cy_time'])) {
                            // 采样日期是否有值，不需要默认值
                            $customer_cy_date = date('Y-m-d', strtotime($row['cy_time']));
                            if ($customer_cy_date != '0000-00-00' && $row_cy_date != '1970-01-01') {
                                $update_date_time_sql = "`cy_date`='{$customer_cy_date}'";
                            } else {
                                $update_date_time_sql = "`cy_date`=NULL";
                            }
                            // 采样时间是否有值，不需要默认值
                            $customer_cy_time = date('H:i:s', strtotime($row['cy_time']));
                            if ($customer_cy_time != '00:00:00') {
                                $update_date_time_sql .= ",`cy_time`='{$customer_cy_time}'";
                            } else {
                                $update_date_time_sql .= ",`cy_time`=NULL";
                            }
                        } else {
                            $update_date_time_sql = "`cy_date`=NULL,`cy_time`=NULL";
                        }
                        if ($row['sample_describe'] == '' && $row['sample_status'] != '') {
                            $row['sample_describe'] = $row['sample_status'];
                        }
                        // 若在委托单中选择了评价标准，则更新cy_rec表中的标准id
                        $cr_jcbz_id_sql = '';
                        if ($row['jcyj']) {
                            $cr_jcbz_id_sql .= ",`jcbz_id` = '{$row['jcyj']}'";
                        }
                        if ($row['xd_fs']) {
                            $cr_jcbz_id_sql .= ",`xd_fs` = '{$row['xd_fs']}'";
                        }
                        if ($global['is_sj_client']) {
                            if ($row['sj_client']) {
                                $cr_jcbz_id_sql .= ",`sj_client` = '{$row['sj_client']}'";
                            }
                        }
                        // customer_rec表json信息
                        $cus_add_json = json_decode($row['sample_add_json'], true);
                        // cy_rec表json信息
                        $rec_json_arr = json_decode($info['json'], true);
                        // 将报告编号类型保存至任务内
                        if ($cus_add_json['report_code_type']) {
                            $rec_json_arr['report_code_type'] = $cus_add_json['report_code_type'];
                        }
                        $rec_json_str = JSON($rec_json_arr);
                        $DB->query("update `customer_rec` set `rec_id`='{$info['id']}' where `id`='{$row['id']}'");
                        $DB->query("update `cy_rec` set {$update_date_time_sql},`ys_zt`='{$row['sample_status']}',`json`='{$rec_json_str}' {$cr_jcbz_id_sql} where `id`='$info[id]'");
                    }
                }
                $kh_info = $DB->fetch_one_assoc("select * from `customer` where  `id` = '{$post['kh_id']}'");
                $kh_info_add_json_arr = json_decode($kh_info['add_json'], true);
                $add_json_sql = '';
                if ($kh_info_add_json_arr['cy_yiju']) {
                    $add_json_sql .= " ,`cy_yiju`='{$kh_info_add_json_arr['cy_yiju']}' ";
                }
                $DB->query("update `cy` set `cy_dept`='{$kh_info['client_name']}',`jcwc_date`='{$kh_info['stipulate_completion_time']}' {$add_json_sql} where id='{$cyd_id}'");
                if ($kh_info['sample_origin'] == 0) {
                    $qz_sql = '';
                    // 委托/采样 单位名称
                    if ($kh_info['client_name']) {
                        $qz_sql .= "`cy_dept`='{$kh_info['client_name']}',";
                    }
                    // 委托/采样 单位地址
                    if ($kh_info['client_address']) {
                        $qz_sql .= "`cy_dept_address`='{$kh_info['client_address']}',";
                    }
                    // 委托/采样 联系人
                    if ($kh_info['liaison']) {
                        $qz_sql .= "`wtdw_lxr`='{$kh_info['liaison']}',";
                    }
                    // 委托/采样 联系电话
                    if ($kh_info['phone_number']) {
                        $qz_sql .= "`wtdw_tel`='{$kh_info['phone_number']}',";
                    }
                    // 委托/采样 联系电话
                    if ($kh_info['phone_number'] && $global['csrw_tel_moren_wtdw']) {
                        $qz_sql .= "`csrw_tzd_tel`='{$kh_info['phone_number']}',";
                    }
                    // 委托/采样 受检单位
                    if ($kh_info['sj_client']) {
                        $qz_sql .= "`wtdw_sjdw`='{$kh_info['sj_client']}',";
                    }
                    // 采样人
                    $cy_users = $global["customer"]['cy_users'] ? $global["customer"]['cy_users'] : '委托方';
                    // 采样人签字
                    $cy_users_qzs = $global["customer"]['cy_users_qzs'] ? $global["customer"]['cy_users_qzs'] : '';
                    // 送样人签字
                    $sy_user_qz = $global["customer"]['sy_user_qz'] ? $global["customer"]['sy_user_qz'] : '';
                    // 将委托单位的送样人信息，同步至cy表
                    if ($global["customer"]['update_cy_user_info'] && $kh_info['liaison']) {
                        $cy_users = $cy_users_qzs = $sy_user_qz = $kh_info['liaison'];
                        // 采样人联系方式
                        if ($kh_info['phone_number']) {
                            $qz_sql .= "`cy_users_tel`='{$kh_info['phone_number']}',";
                        }
                    }
                    $qz_sql .= "`cy_user`='{$cy_users}', `cy_users`='{$cy_users}',";
                    if ($cy_users_qzs) {
                        $qz_sql .= "`cy_users_qzs`='{$cy_users_qzs}',`cy_user_qz_date`='" . date('Y-m-d') . "',";
                    }
                    if ($sy_user_qz) {
                        $qz_sql .= "`sy_user_qz`='{$sy_user_qz}',`sy_user_qz_date`='" . date('Y-m-d') . "',";
                    }
                    $qz_sql = trim($qz_sql, ',');
                    if ($qz_sql != '') {
                        $DB->query("update `cy` set {$qz_sql} where id='{$cyd_id}'");
                    }
                }
            } else {
                $DB->query("update `kehu` set `cyd_id`='$cyd_id' where `id` = '$post[kh_id]'");
                $query = $DB->query("select * from `kh_rec` where `kh_id`='$post[kh_id]' and `act`='1'");
                while ($row = $DB->fetch_assoc($query)) {
                    $info = $DB->fetch_one_assoc("select * from `cy_rec` where `cyd_id`='$cyd_id' and `site_name`='$row[yp_name]'");
                    if (!empty($info['id'])) {
                        $DB->query("update `cy_rec` set `cy_date`='$row[cy_time]',`ys_zt`='$row[yp_status]' where `id`='$info[id]'");
                        $DB->query("update `kh_rec` set `rec_id`='$info[id]' where `id`='$row[id]'");
                    }
                }
            }
            if ($post["cy_flag"] == '1') {
                return true;
//            echo "<script>alert('任务生成成功');location.href='$rooturl/cy/modi_csrw_tzd.php?cyd_id={$cyd_id}';</script>";
            } else {
                if ($yanshou_peizhi == '有验收') {
                    return true;
//                echo "<script>alert('任务生成成功');location.href='$rooturl/cy/cy_ys.php?cyd_id={$cyd_id}';</script>";
                } else {
                    return true;
//                echo "<script>alert('任务生成成功');location.href='$rooturl/cy/cy_record.php?cyd_id={$cyd_id}';</script>";
                }
            }
            exit;
        }
        // 生成检测任务时，将样品的评价标准，存入<检测任务通知单>中的<检测依据>字段
        if ($global['csrw_tzd']['mr_jc_yiju']) {
            $all_jcbz_bh = get_all_jcbz_bh();
            foreach ($cyd_arr as $cyd_id) {
                // 查询本批次样品的评价标准
                $sql = "SELECT `cy`.`jc_yiju`, `cy_rec`.`jcbz_id`
					FROM `cy`
					LEFT JOIN `cy_rec` ON `cy`.`id`=`cy_rec`.`cyd_id`
					WHERE `cy`.`id` = '{$cyd_id}'
					GROUP BY `cy_rec`.`jcbz_id`
				";
                $query = $DB->query($sql);
                $jc_yiju_arr = [];
                $jc_yiju_str = '';
                // 本批次任务，检测任务通知单中的<检测依据>字段是否为空
                $jc_yiju_is_null = true;
                while ($row = $DB->fetch_assoc($query)) {
                    $jc_yiju_arr[] = $all_jcbz_bh[$row['jcbz_id']];
                    $row['jc_yiju'] ? $jc_yiju_is_null = false : '';
                }
                // 若<检测依据>非空，则不再更新
                if (!$jc_yiju_is_null) {
                    continue;
                }
                $jc_yiju_str = join($jc_yiju_arr, '、');
                $update_sql = "UPDATE `cy` SET `jc_yiju` = '{$jc_yiju_str}' WHERE `id` = '{$cyd_id}'";
                $DB->query($update_sql);
            }
        }
        $cyd_ids = implode(",", $cyd_arr);
        if (isset($post['url']) && !empty($post['url'])) {
            $cyd_ids = $post['url'];
        }
        return $cyd_ids;
    } else {
        var_dump(123);
        return false;
//    echo "<script>alert('未选择站点');location.href='$rooturl/xd_cyrw/xd_cyrw_index.php?site_type={$post['site_type']}';</script>";
    }
    return true;
}
////获取历史委托单
//function getCustomer(){
//
//}

//获取默认显示格式
function getTemplates(){
    global $DB,$dw_biaozhi ,$global;
    include_once "../customer_manage/get_code.php";
    $individual_dir_name = "../customer_manage/json/{$dw_biaozhi}";
    if (!file_exists("{$individual_dir_name}/customer_add_field.json")){
        $individual_dir_name = "../customer_manage/json/default";
    }
// 获取格式信息
    $customer_info_all_json = file_get_contents("{$individual_dir_name}/customer_add_field.json");
    $geshi_n_set_sql = $DB->query("SELECT * FROM `n_set` WHERE `module_name`='template_value' AND `act`='1' ORDER BY `module_value5`+0 ASC, `id`");
    $geshi_arr = [];
    while($row = $DB->fetch_assoc($geshi_n_set_sql)){
        $geshi_arr[$row['id']] = $row['module_value1'];
    }
    $template_value = $geshi_arr;
    $template_value_json = JSON($template_value);


    $morengeshi_id_info = $DB->fetch_one_assoc("SELECT * FROM `n_set` WHERE `module_name`='template_value' AND `act`='1' AND `id` = 3085  ORDER BY `module_value5`+0 ASC, `id`");
    $default_template_id = $morengeshi_id_info['id'];

    $n_set_table_header_sql = "SELECT * FROM `n_set` WHERE `module_name`='customer_add_field' AND `module_value1`='{$default_template_id}'";
    $n_set_table_header_str = $DB->fetch_one_assoc($n_set_table_header_sql);
    $n_set_table_header_str = $n_set_table_header_str["module_value2"];
    $n_set_table_header = json_decode($n_set_table_header_str, true)['show_field'];

    $template_site_type = JSON($global['site_type']);
    $customer_info_all_json = str_replace(['__template_value__', '__template_default_selected_value__','__template_site_type_val__'], [$template_value_json, $default_template_id,$template_site_type], $customer_info_all_json);
    $customer_info_all_json = str_replace('_sample_origin_default_value_', $global['customer']['sample_origin'], $customer_info_all_json);
    $customer_info_all_json_arr = json_decode($customer_info_all_json, true);
    if (!in_array( "委托单格式",$n_set_table_header)) {
        $n_set_table_header[] = "委托单格式";
    }
    //select1 不需要序列化处理的字段
    $no_serialize = ['sample_manage'];
    //select1 不需要处理的字段
    $no_serialize2 = ['sample_type' , 'jcyj'];
    //select2 需要处理的字段
    $no2_serialize2 = ['xd_fs'];
    foreach ($customer_info_all_json_arr as $group => $gv) {
        if($group == '个性配置'){
            continue;
        }
        $customer_info_arr[$group] = [];
        foreach ($gv as $k => $v) {
            if($v['config']['mode'] == 'none' || $v['config']['mode'] == 'button'){
                unset($gv[$k]);
                continue;
            }
            if($v['field'] == 'code'){
                $v['value']= get_customer_code();
            }

            if (array_search($v['headerName'], $n_set_table_header) !== false || $v['selected']) {
                if($v['config']['mode'] == 'select1'){
                    if(in_array($v['field'] , $no_serialize)){
                        if(!in_array($v['field'] , $no_serialize2)) {
                            $d_v = [];
                            foreach ($v['config']['default_value'] as $key => $value) {
                                $d_v[] = [
                                    "value" => $value,
                                    "text" => $value
                                ];
                            }
                        }
                    }else{
                        $i = 0;
                        $d_v = [];
                        foreach($v['config']['default_value'] as $key => $value){
                            $d_v[] = [
                                "value" => $i,
                                "text" => $value
                            ];
                            $i++;
                        }
                    }
                    if($v['field'] != 'sample_type' || $v['field'] != 'jcyj'){
                        $v['config']['default_value'] = $d_v;
                    }
                }
                if($v['config']['mode'] == 'select2') {
                    $defa_arr = [];
                    foreach ($v['config']['default_value'] as $default_k => $default_v){
                        if(in_array($v['field'] , $no2_serialize2)){
                            $defa_arr[] = [
                                "value" => $default_k,
                                "text" => $default_v
                            ];
                        }else{
                            $defa_arr[] = [
                                "value" => $default_v,
                                "text" => $default_v
                            ];
                        }

                    }
                    $v['config']['default_value'] = $defa_arr;
                }
                $customer_info_arr[$group][$v['headerName']] = $v;
            }

        }
    }
    return $customer_info_arr;
}
function insertSql($db_table, $data, $addData=[])
{
    if ($addData) {
        foreach ($addData as $key => $addDatum) {
            $data[$key] = $addDatum;
        }
    }
    $insertKeys = "`" . implode("`,`", array_keys($data)) . "token`";
    foreach ($data as &$v){
        if(empty($v)){
            $v = '0';
        }
    }
    $insertValues = "'" . implode("','", $data) . "'";
    return "insert into {$db_table} ({$insertKeys}) values ({$insertValues})";
}

function getWeixinOpenid($wexin_code){
    $appid = 'wxc772664858780284';
    $appsecret = '2fb3f9d85db3a9209e602d3509d12865';
    $code = $wexin_code; // 这个code需要你从小程序端获取

    $params = [
        'appid' => $appid,
        'secret' => $appsecret,
        'js_code' => $code,
        'grant_type' => 'authorization_code'
    ];

    $token_access_url = "https://api.weixin.qq.com/sns/jscode2session?" . http_build_query($params);

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $token_access_url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    $result = curl_exec($curl);
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
//    $path =  '/var/www/lims3/customer_cy/wx.log';
//    $lines = file_get_contents($path);
////    var_dump((array)json_decode($lines));die;
//    $file = fopen($path, 'w+');
//    $text = date('Y-m-d H:i:s') . "   :";
//    $text .= json_encode($result);
//    fwrite($file, $text);
//    fclose($file);
//    $result = '{"session_key":"tEAZTxCFwyfoopVQANNDDA==","openid":"ol_0X4-SRlzORf4IFkQmCYphBqnU"}';
    if ($result === false) {
//        echo 'Curl error: ' . curl_error($curl);
        return ['code' => false, 'msg' => '参数错误'];
    } else {
        $json = json_decode($result, true);
        if (isset($json['openid'])) {
            $openid = $json['openid'];
            return ['code' => true, 'msg' => $openid];
//            return $openid;
        } else {
//            echo "获取token失败";
//            echo 'HTTP Code: ' . $httpCode;
            return ['code' => false, 'msg' => json_decode($result,true)['errmsg']];;
        }
    }

    curl_close($curl);
    return false;
}
function addWxUser($openid){
    global $DB;

    $token = base64_encode(time());
    $sql = "INSERT INTO `wx_user` SET `wx_openid` = '$openid' ,`token` = '$token' ";
    $DB->query($sql);
    if($DB->insert_id()){
        return  $token;
    }else{
        return false;
    }
}
function getWxUser($token){
    global $DB;

    $wx_user = $DB->fetch_one_assoc("SELECT * FROM `wx_user` WHERE  `token`='{$token}'");
    if($wx_user){
        return $wx_user['wx_openid'];
    }else{
        return false;
    }
}
function getHistory($openid , $status = ''){
    global $DB;
    if(!$status){
        $customer_sql = "
            SELECT cu.id,cu.cyd_id,cu.code,cu.client_name,cu.liaison,cyd.cyd_bh,cyd.status 
            FROM `customer` as cu 
            LEFT JOIN `cy` as cyd  
            ON cu.cyd_id=cyd.id 
            WHERE  cu.wx_user like '%{$openid}%' ";

    }else{
        if($status == 1){
            $where = ' and cyd_id = 0';
        }else if ($status == 2){
            $where = 'and (cyd.status = 4 or cyd.status = 1) ';
        }else if ($status == 3){
            $where = 'and (cyd.status > 6) ';
        }
        $customer_sql = "
            SELECT cu.id,cu.cyd_id,cu.code,cu.client_name,cu.liaison,cyd.cyd_bh,cyd.status 
            FROM `customer` as cu LEFT JOIN `cy` as cyd  
            ON cu.cyd_id=cyd.id 
            WHERE  cu.wx_user like '%{$openid}%' $where";
    }
//    echo $customer_sql;
//    die;
    $customer_query = $DB->query($customer_sql);
    $customer_arr = [];
    while ($row = $DB->fetch_assoc($customer_query)) {
        $customer_arr[] = $row;
    }
    if($status == 4){
        $sql = "SELECT id,cyd_id,code,client_name,liaison 
            FROM `customer` WHERE  cu.wx_user like '%{$openid}%'";
        $customer_query = $DB->query($sql);
        $customer_arr = [];
        while ($row_cus = $DB->fetch_assoc($customer_query)) {
            $sql_rec = "SELECT id,rec_id,site_name FROM `customer_rec` WHERE  customer_id = {$row_cus['id']}";
            $query_rec = $DB->query($sql_rec);
            $rec = [];
            while ($row_rec = $DB->fetch_assoc($query_rec)) {
                $rec_v['site_name'] = $row_rec['site_name'];
                if($row_rec['rec_id'] > 0){
                    $row_assay = $DB->fetch_one_assoc("SELECT id,rec_id,site_name FROM `assay_report` WHERE  single_cid = {$row_rec['rec_id']}");
                    if($row_assay){
                        $report_detail = $DB->fetch_one_assoc("SELECT archive FROM `assay_report_detail` WHERE  report_id = {$row_assay['id']}");
                        $rec_v['archive'] = $report_detail['archive'];
                    }
                }
                $rec[] = $rec_v;
            }
            $row_cus['customer_rec'] = $rec;
            $customer_arr[] = $row_cus;
        }
    }
    return $customer_arr;
}
